// Create, Read, and search file Program
import java.util.*;
import java.io.*;
class StudentRec
{
int regNo;
String name;
int internalMarks;
void displayRecord()
{
System.out.print("RegNo.: " + regNo);
System.out.print(" Name:
" + name);
System.out.println(" Internal marks: "+ internalMarks);
}
}
class CreateReadFile {
public static void main(String args[])
throws IOException {
int i,num;
int choice=0;
int searchRegNo=0;
String str="";
boolean flag=true;
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
StudentRec record = new
StudentRec();
while(flag)
{
System.out.println("\n
Menu");
System.out.println("1. Write File");
System.out.println("2. Search");
System.out.println("3. Display File");
System.out.println("4. Quit");
System.out.print("Enter your choice: ");
choice= Integer.parseInt(br.readLine());
switch(choice){
case 1:
// Create a file.
FileWriter fout =
new FileWriter("test.txt");
//Read data from
Keyboard
System.out.print("How
many records? ");
num=
Integer.parseInt(br.readLine());
for(i=0;i<num;i++)
{
System.out.print("enter
student id: ");
record.regNo=
Integer.parseInt(br.readLine());
System.out.print("Enter
student name:");
record.name=br.readLine();
System.out.print("enter
Internalmarks:");
record.internalMarks =Integer.parseInt(br.readLine());
// Write to file.
fout.write(record.regNo+"\n");
fout.write(record.name+"\n");
fout.write(record.internalMarks+"\n");
}
fout.write("EOF");
fout.close();
System.out.println("File
is created");
break;
case 2:
System.out.print("enter
search Id: ");
searchRegNo =
Integer.parseInt(br.readLine());
case 3:
FileReader fin =
new FileReader("test.txt");
Scanner sc = new
Scanner(fin);
while(sc.hasNextInt())
{
//Read data from
file
record.regNo =
sc.nextInt();
record.name =
sc.next();
record.internalMarks=
sc.nextInt();
if(choice==3)
record.displayRecord();
if(choice==2)if(record.regNo==searchRegNo)
record.displayRecord();
}
str= sc.next();
if(str.equals("EOF"))
System.out.println("End
of file");
else
System.out.println("File format error.");
fin.close();
break;
case 4: flag=false;
break;
default:System.out.println("Wrong Choice!!");
}
}
System.out.println("Program is over");
}
No comments:
Post a Comment