Java


Java Tutorial


Admission Enquiry Form

  


Serialization and Deserialization in Java


Java Code for Serialization:

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.Serializable;

class Student implements Serializable
{
     String stname;
     int rollno;
     double fee;
     public Student()
     {
          stname="Guleria";
          rollno=177;
          fee=45000.00;
     }//end of function
     public void setData(String stname,int rollno,double fee)
     {
          this.stname=stname;
          this.rollno=rollno;
          this.fee=fee;
     }//end of function
     public void getData()
     {
          System.out.println("Name of the student is " + stname);
          System.out.println("Roll no of student is " + rollno);
          System.out.println("Fee of student is " + fee);
     }//end of function

}//end of class student
public class ExampleSerialization {
     public static void main(String[] args)throws IOException
      {
          Student st=new Student();
          FileOutputStream fos=new FileOutputStream("objectoutput.txt");
          ObjectOutputStream oos=new ObjectOutputStream(fos);
          oos.writeObject(st);
          System.out.println("St object written in file");
          st.setData("Shivang", 178, 6000);
          oos.writeObject(st);
          System.out.println("st object written with different data");
          fos.close();
    }//end of main     
}//end of class




Java Code for Deserialization:

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

class Student implements Serializable
{
     String stname;
     int rollno;
     double fee;
     public Student()
     {
        //  stname="Guleria";
         // rollno=177;
         // fee=45000.00;
     }//end of function
     public void setData(String stname,int rollno,double fee)
     {
          this.stname=stname;
          this.rollno=rollno;
          this.fee=fee;
     }//end of function
     public void getData()
     {
          System.out.println("Name of the student is " + stname);
          System.out.println("Roll no of student is " + rollno);
          System.out.println("Fee of student is " + fee);
     }//end of function

}//end of class student
public class ExampleDeserialization {
     public static void main(String[] args)throws IOException,ClassNotFoundException
      {
          Student st=new Student();
          FileInputStream fis=new FileInputStream("objectoutput.txt");
          ObjectInputStream ois=new ObjectInputStream(fis);
         // while()
          st=(Student)ois.readObject();
          st.getData();
          st=(Student)ois.readObject();
          st.getData();
          st=(Student)ois.readObject();
          st.getData();
          fis.close();
       }//end of main     
}//end of class