ObjectOutputStream and ObjectInputStream is use to store object data type value in file in java.This program five employee details take and store txt file and user can show all employee details and search employee details by employee name.
CODING:
import java.io.*;
import java.util.Scanner;
public class data{
public static void main(String[] args)throws IOException, ClassNotFoundException{
int ch=0;
emp temp;
Scanner s=new Scanner(System.in);
File f=new File("emp.txt");
ObjectOutputStream out=new ObjectOutputStream(new FileOutputStream(f));
for(int i=0;i<5;i++){
emp obj=new emp();
obj.get();
out.writeObject(obj);
}
out.close();
ObjectInputStream in=new ObjectInputStream(new FileInputStream(f));
do{
System.out.println("\n1.Display\n2.Search\n3.Exit\nChoice ");
ch=s.nextInt();
switch(ch){
case 1:
for(int i=0;i<5;i++){
temp=(emp)in.readObject();
temp.disp();
}
out.close();
break;
case 2:
int flag=0;
ObjectInputStream ser=new ObjectInputStream(new FileInputStream(f));
System.out.println("Enter Name");
String na=s.next();
for(int i=0;i<5 && flag==0;i++){
temp=(emp)ser.readObject();
if(temp.name.equals(na)){
temp.disp();
flag=1;
}
}
if(flag==0){
System.out.println("Not Found");
}
break;
case 3:break;
default:System.out.println("Try Again");
}
}while(ch!=3);
}
}
class emp implements Serializable{
int id;
String name;
public void get(){
Scanner sc=new Scanner(System.in);
System.out.print("Enter id ");
id=sc.nextInt();
System.out.print("Enter Name ");
name=sc.next();
}
public void disp(){
System.out.println("Id "+id+" Name "+ name);
}
}
import java.util.Scanner;
public class data{
public static void main(String[] args)throws IOException, ClassNotFoundException{
int ch=0;
emp temp;
Scanner s=new Scanner(System.in);
File f=new File("emp.txt");
ObjectOutputStream out=new ObjectOutputStream(new FileOutputStream(f));
for(int i=0;i<5;i++){
emp obj=new emp();
obj.get();
out.writeObject(obj);
}
out.close();
ObjectInputStream in=new ObjectInputStream(new FileInputStream(f));
do{
System.out.println("\n1.Display\n2.Search\n3.Exit\nChoice ");
ch=s.nextInt();
switch(ch){
case 1:
for(int i=0;i<5;i++){
temp=(emp)in.readObject();
temp.disp();
}
out.close();
break;
case 2:
int flag=0;
ObjectInputStream ser=new ObjectInputStream(new FileInputStream(f));
System.out.println("Enter Name");
String na=s.next();
for(int i=0;i<5 && flag==0;i++){
temp=(emp)ser.readObject();
if(temp.name.equals(na)){
temp.disp();
flag=1;
}
}
if(flag==0){
System.out.println("Not Found");
}
break;
case 3:break;
default:System.out.println("Try Again");
}
}while(ch!=3);
}
}
class emp implements Serializable{
int id;
String name;
public void get(){
Scanner sc=new Scanner(System.in);
System.out.print("Enter id ");
id=sc.nextInt();
System.out.print("Enter Name ");
name=sc.next();
}
public void disp(){
System.out.println("Id "+id+" Name "+ name);
}
}
Comments
Post a Comment