Introduction To Deserialization In Java

Introduction

 
In this article, we discuss Deserialization in Java.
 

Deserialization

 
Deserialization is the reverse of serialization, in other words, deserialization extracts the data from a series of bytes. It is a process of converting the data from files or a database into a stream of bytes using class objects.
It is the process of reconstructing objects from the serialized state. We can simply say it is the reverse of serialization.
The following figure illustrates a lot about deserialization in Java.
deserialization.jpg

Sample Constructor

 
The following is a sample of a commonly used constructor; this creates an ObjectInputStream that reads from the specified input:
 
ObjectInputStream (InputStream in) throws IOException {}
 

Sample Method

 
The following is a sample of a commonly used method; this creates an object from the input stream:
 
final Object readObject() throws IOException, ClassNotFoundException {}
 
Example
 
In this example we can deserialize a class "Serialization", this class contains a student's record in serialized format and hence we must print a record in the deserialized class. i.e "500, John" as in the following:
  1. import java.io.Serializable;  
  2. public class Interface implements Serializable  
  3.   {  
  4.     int sid;  
  5.     String name;  
  6.     public Interface(int sid, String name)  
  7.       {  
  8.         this.sid = sid;  
  9.         this.name = name;  
  10.       }  
  11.   }   
  1. import java.io.*;  
  2. class SerializationEx1  
  3.   {  
  4.     public static void main(String args[])throws Exception  
  5.       {  
  6.         Interface st =new Interface(500,"John");  
  7.         FileOutputStream fout=new FileOutputStream("p.txt");  
  8.         ObjectOutputStream out=new ObjectOutputStream(fout);  
  9.         out.writeObject(st);  
  10.         out.flush();  
  11.         System.out.println("you have successfully saved your record");  
  12.       }  
  13.   }  
  1. import java.io.*;  
  2. class DeSerializationEx  
  3.   {  
  4.     public static void main(String args[])throws Exception  
  5.       {  
  6.         ObjectInputStream in=new ObjectInputStream(new FileInputStream("p.txt"));  
  7.         Interface s=(Interface)in.readObject();  
  8.         System.out.println(s.sid+" "+s.name);  
  9.         in.close();  
  10.       }  
  11.   }  
Output 
pic-1.jpg


Similar Articles