(Meta Program) Serialization And Deserialization using files (Alternative) in Java
CODE :
import java.lang.*;
import java.util.*;
import java.io.*;
class Serial{
public static void savedata(int i,ArrayList<String>data)throws IOException{
String a;
if(i==0){
a = "fnames";}
else if(i==1){
a = "lnames";}
else if(i==2){
a = "pnames";}
else{
a = "phnos";}
FileOutputStream writeData = new FileOutputStream(a+".ser");
ObjectOutputStream writeStream = new ObjectOutputStream(writeData);
writeStream.writeObject(data);
writeStream.flush();
writeStream.close();}
public static ArrayList<String> readdata(int i)throws IOException{
String a;
if(i==0){
a = "fnames";}
else if(i==1){
a = "lnames";}
else if(i==2){
a = "pnames";}
else{
a = "phnos";}
ArrayList<String> b = new ArrayList<String>();
ArrayList<String> fnames = new ArrayList<String>();
ArrayList<String> lnames = new ArrayList<String>();
ArrayList<String> pnames = new ArrayList<String>();
ArrayList<String> phnos = new ArrayList<String>();
FileInputStream readData = new FileInputStream(a+".ser");
ObjectInputStream readStream = new ObjectInputStream(readData);
try{
if(i==0){
b = fnames;
}
else if(i==1){
b = lnames;
}
else if(i==2){
b = pnames;
}
else if(i==3){
b = phnos;
}
b = (ArrayList<String>) readStream.readObject();
readStream.close(); }catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
return b;
}
public static void main(String args[])throws IOException{
Scanner sc = new Scanner(System.in);
ArrayList<String> fnames = new ArrayList<String>();
ArrayList<String> lnames = new ArrayList<String>();
ArrayList<String> pnames = new ArrayList<String>();
ArrayList<String> phnos = new ArrayList<String>();
int x=0;
while(x==0){
System.out.print("Enter Your First Name: ");
String fname = sc.next();
System.out.print("Enter Your Last Name: ");
String lname = sc.next();
System.out.print("Enter Your Parent Name: ");
String pname = sc.next();
System.out.print("Enter Your Phone Number: ");
String phno = sc.next();
fnames.add(fname);
lnames.add(lname);
pnames.add(pname);
phnos.add(phno);
savedata(0,fnames);
savedata(1,lnames);
savedata(2,pnames);
savedata(3,phnos);
System.out.println("0. Enter another Person Details, 1.Print Person Details");
x = sc.nextInt();}
ArrayList a = (ArrayList)readdata(0).clone();
ArrayList b = (ArrayList)readdata(1).clone();
ArrayList c = (ArrayList)readdata(2).clone();
ArrayList d = (ArrayList)readdata(3).clone();
for(int i=0; i<a.size(); i++)
{
System.out.println("S.no : "+i+" |Name : "+a.get(i)+" "+b.get(i)+" |Parent Name : "+c.get(i)+" |Phno : "+d.get(i)); }
}}
Inputs And Outputs :
Folders :