What is Serialization and How it works ?

What is Serialization ?

Object serialization is the process of saving an object's state to a sequence of bytes, as well as the process of rebuilding those bytes into a live object at some future time. The Java Serialization API provides a standard mechanism for developers to handle object serialization.

  • Allows the persistent storage of objects
  • Uses the java.io.Serializable interface
  • ObjectInputStream and ObjectOutputStream
  • Allows you to save objects to file and load them at a later date
  • Really should only be used for temporary storage of objects

What is actually saved?

  • Only class name and object’s data is saved
  • If that data is an object, it is also saved
  • Each object is given a serial number
  • If an object has already been saved (e.g. within a graph) then only the serial number is saved
  • Methods are not saved
  • Static information not saved 

Making an object serializable :

  1. Implement the Serializable interface
    • Does not require any methods to be implemented
  2. Implement the Externalizable interface
    • default behaviour only saves class name
    • must implement readExternal and writeExternal

To save the objects to file:

FileOutputStream file = new FileOutputStream("data.ser");
ObjectOutputStream output = new ObjectOutputStream(file);

To load the objects from file:

FileInputStream file = new FileInputStream("data.ser");
ObjectInputStream input = new ObjectInputStream(file);
Family family = (Family) input.readObject();

Note: .ser file naming convention.