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 illustrate a lot about deserialization in Java.
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:
import java.io.Serializable;
public class Interface implements Serializable
{
int sid;
String name;
public Interface(int sid, String name)
{
this.sid = sid;
this.name = name;
}
}
import java.io.*;
class SerializationEx1
{
public static void main(String args[])throws Exception
{
Interface st =new Interface(500,"John");
FileOutputStream fout=new FileOutputStream("p.txt");
ObjectOutputStream out=new ObjectOutputStream(fout);
out.writeObject(st);
out.flush();
System.out.println("you have successfully saved your record");
}
}
import java.io.*;
class DeSerializationEx
{
public static void main(String args[])throws Exception
{
ObjectInputStream in=new ObjectInputStream(new FileInputStream("p.txt"));
Interface s=(Interface)in.readObject();
System.out.println(s.sid+" "+s.name);
in.close();
}
}
Output