Wednesday, 30 November 2016

Program to store the entered details (records) in a file named "stud.dat"

In this program, we have read the details of students like roll no, name, marks1, marks2 and store them in a file using DataOutputStream class. The DataOutputStream stream lets you write the primitives to an output source. Following is the constructor to create a DataOutputStream.
DataOutputStream  out  =  DataOutputStream( OutputStream  out);

PROGRAM
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.util.Scanner;

class StoreRecordInFile {

 public static void main(String[] args) {

  try
  {
   File f=new File("stud.dat");
   FileOutputStream fos=new FileOutputStream(f);
   DataOutputStream dos=new DataOutputStream(fos);
   
   Scanner s=new Scanner(System.in);
   int roll_no,m1,m2;
   String name;
   
   System.out.println("Enter the data for three students : ");
   for(int i=1;i<=3;i++)
   {
    System.out.println("Enter Roll no, Name, Marks of M1, Marks of M2 =>");
    roll_no = s.nextInt();
    name = s.nextLine();
    m1 = s.nextInt();
    m2 = s.nextInt();
    
    dos.writeInt(roll_no);
    dos.writeUTF(name);
    dos.writeInt(m1);
    dos.writeInt(m2);
   }
   
   System.out.println("Record saved successfully...");
   dos.close();
  }
  catch(Exception ee){
   System.out.println(ee.getMessage());
   ee.printStackTrace();
  }
 }
}
OUTPUT
C:\>javac StoreRecordInFile.java
C:\>java StoreRecordInFile
Enter the data for three students :
Enter Roll no, Name, Marks of M1, Marks of M2 =>
4 Rohan
75 87
Enter Roll no, Name, Marks of M1, Marks of M2 =>
5 Darshan
65 70
Enter Roll no, Name, Marks of M1, Marks of M2 =>
8 Subhash
61 49
Record saved successfully...

No comments:

Post a Comment