Serialization in java provides a thing known as object serialization.It means that an object can be represented as a sequence of bytes which includes object data as well as information about the object type and information of data stored in object.Classes ObjectInputStream and ObjectOutputStream are high level streams which is defined for serializing and deserializing an object.
ObjectOutputStream Syntax:
public final void writeObject(Object x) throws IOException.
The above method serializes an object and sends it to the output stream.
ObjectInputStream Syntax:
public final Object readObject() throws IOException,ClassNotFoundException.
The above method retrieves the next object out of stream and deserializes it.
Example:
public class Employee implements java.io.Serializable { public String name; public String address; public transient int SSN; public int number; public void mailCheck() { System.out.println("Mailing a check to " + name + " " + address); } }
Here the class Employee implements the serializable interface.
Conditions needs to be met for successful serialization:
1.Class must implement the java.io.Serializable interface.
2.All of the fields in the class must be serializable. If a field is not serializable, it must be marked transient.
Serializing an object:
import java.io.*; public class SerializeDemo { public static void main(String [] args) { Employee e = new Employee(); e.name = "Reyan Ali"; e.address = "Phokka Kuan, Ambehta Peer"; e.SSN = 11122333; e.number = 101; try { FileOutputStream fileOut = new FileOutputStream("/tmp/employee.ser"); ObjectOutputStream out = new ObjectOutputStream(fileOut); out.writeObject(e); out.close(); fileOut.close(); System.out.printf("Serialized data is saved in /tmp/employee.ser"); }catch(IOException i) { i.printStackTrace(); } } }
Here the above program is used to serialize an object.SerializeDemo instanties an employee object and serializes it to a file.After this program executed a file named employee.ser is created.It doesnt generate any output but it provides a file with .ser extension.
Deserializing an object
import java.io.*; public class DeserializeDemo { public static void main(String [] args) { Employee e = null; try { FileInputStream fileIn = new FileInputStream("/tmp/employee.ser"); ObjectInputStream in = new ObjectInputStream(fileIn); e = (Employee) in.readObject(); in.close(); fileIn.close(); }catch(IOException i) { i.printStackTrace(); return; }catch(ClassNotFoundException c) { System.out.println("Employee class not found"); c.printStackTrace(); return; } System.out.println("Deserialized Employee..."); System.out.println("Name: " + e.name); System.out.println("Address: " + e.address); System.out.println("SSN: " + e.SSN); System.out.println("Number: " + e.number); } }
The above program provides the following result by deserializing the employee object
Deserialized Employee…
Name: Reyan Ali
Address:Phokka Kuan, Ambehta Peer
SSN: 0
Number:101