20 How to create object using De-serialization Concept in Java?

In this first I am serializing the student data into the file "des" and after that de-serializing the same data into an object and Printing all that data.

SAnD.java

import java.io.FileOutputStream;
import java.io.FileInputStream;
import java.io.ObjectOutputStream;
import java.io.ObjectInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

class Student implements java.io.Serializable{
int sid = 101;
String sname = "ram";
int sage = 17;
double sfee = 2500;
String scourse = "java";
String insName = "CodingAtharva";
}

class SAnD{
public static void main( String[] args)
throws FileNotFoundException,IOException,
ClassNotFoundException{

FileOutputStream fos = new FileOutputStream("des");
ObjectOutputStream oos = new ObjectOutputStream(fos);

Student s = new Student();
oos.writeObject(s);  /* Serializing the data*/

FileInputStream fis = new FileInputStream("des");
ObjectInputStream ois = new ObjectInputStream(fis);
Object o = ois.readObject(); /* De-Serializing the data*/
Student s1 = (Student)o; /* Upcasting */
System.out.println(s1.sid);
System.out.println(s1.sname);
System.out.println(s1.sage);
System.out.println(s1.sfee);
System.out.println(s1.scourse);
System.out.println(s1.insName);
}

}

Output:  


des 

Previous
Next Post »