Serialization and Deserialization Concept in Java:-
.................................................................................................................................

Serialization means convert object data to Stream and deserialization means Convert Stream to Object.

Stream means the Sequence of bytes.

for example, if we store student data into student objects and we want to write Student object data to file then we will use data serialization.


If we have Student data in the file and we want to co-relate file data to object then we can use de-serialization.



Java provides a Serializable Interface to implement Serialization this interface does not contain any method it only contains behavior hence It is also called Marker Interface.



Java Provide ObjectOuputStream Class and ObjectInputStream Class to Write and Read Data into Object.




 
Complete Example of Serialization and De-serialization?

import java.io.*;
class Student implements Serializable
{
   int rno;
   String sname;
   Student(int rno,String sname)
   {
      this.rno=rno; 
      this.sname=sname;

   } 

}
class SerExample
{
     public static void main(String args[])  throws

IOException,ClassNotFoundException
     {
         File f = new File("mno.txt");
         /*Student obj = new Student(1001,"xyz");
        
         FileOutputStream fo = new FileOutputStream(f);
         ObjectOutputStream oo = new ObjectOutputStream(fo);
         oo.writeObject(obj);
         fo.close(); */
         Student obj1=null;
         FileInputStream fi = new FileInputStream(f);
         ObjectInputStream oi = new ObjectInputStream(fi);
         obj1 = (Student)oi.readObject();
         System.out.print(obj1.rno+" ,"+obj1.sname);
         
       

     }




Post a Comment

If you have any doubt in programming or join online classes then you can contact us by comment .

Previous Post Next Post