Download as pdf or txt
Download as pdf or txt
You are on page 1of 4

import java.io.

*;
import java.util.*;
public class BinFiles
{
String name; int age; double marks;
static Scanner in = new Scanner(System.in);
static Scanner sc = new Scanner(System.in);

void addrecord()throws IOException


{
DataOutputStream out = new DataOutputStream(new
FileOutputStream("Stud.dat",true));
try
{
for(int i = 1 ; i<=2;i++)
{
System.out.println("enter a name, age and marks ");
name = in.nextLine();
age = sc.nextInt();
marks = sc.nextDouble();
out.writeUTF(name);
out.writeInt(age);
out.writeDouble(marks);
}
out.close();
}
catch(IOException e)
{
System.out.print(e);
}
}

void print()throws IOException


{
//reading data from the file
boolean eofile = false;
try
{
DataInputStream in = new DataInputStream(new FileInputStream("Stud.dat"));
do
{
try
{
name = in.readUTF();
age = in.readInt();
marks = in.readDouble();
//if(marks>=90)
System.out.println(name+"\t"+age+"\t"+marks);
}
catch(EOFException e)
{
eofile = true;
}
}while(!eofile);
in.close();
}
catch(FileNotFoundException ee)
{
System.out.println("File not found");
}
}

void update()throws IOException


{
DataOutputStream out1 = new DataOutputStream(new
FileOutputStream("temp.dat"));
String nm;double mm;
System.out.println("Enter name for search");
nm = in.nextLine();
System.out.println("Enter changed marks ");
mm = sc.nextDouble();
boolean eofile = false;
try
{
DataInputStream in1 = new DataInputStream(new FileInputStream("Stud.dat"));
do
{
try
{
name = in1.readUTF();
age = in1.readInt();
marks = in1.readDouble();
if(name.compareTo(nm)==0)
marks=mm;
out1.writeUTF(name);
out1.writeInt(age);
out1.writeDouble(marks);
}
catch(EOFException e)
{
eofile = true;
}
}while(!eofile);
in1.close();
out1.close();
}
catch(FileNotFoundException eee)
{
System.out.println("File does not exists ");
}
DataInputStream in2 = new DataInputStream(new FileInputStream("temp.dat"));
DataOutputStream out2 = new DataOutputStream(new
FileOutputStream("Stud.dat"));
eofile=false;
do
{
try
{
name = in2.readUTF();
age = in2.readInt();
marks = in2.readDouble();
out2.writeUTF(name);
out2.writeInt(age);
out2.writeDouble(marks);
}
catch(EOFException e)
{
eofile = true;
}
}while(!eofile);
out2.close();
in2.close();
}

public static void main()throws IOException


{
int ch=0;
BinFiles obj = new BinFiles();

do
{
System.out.println("1 . Add records ");
System.out.println("2 . Update records ");
System.out.println("3 . Display records ");
System.out.println("4 . Exit");
System.out.println("Enter your choice ");
ch = sc.nextInt();
switch(ch)
{
case 1:obj.addrecord();
break;
case 2:obj.update();
break;
case 3:obj.print();
break;
case 4:System.exit(0);
break;
default :System.out.println("Wrong choice entered ");
}
}while(ch!= 4);
}
}

You might also like