Tuesday, September 29, 2009

Serialization

Serialization is a technique to write object's state to a data file. In order to be able to write the object to a file the class whose instance (object) we need to write has to implement the marker interface Serializable. This interface does not contain any methods.There are two methods that we use to serialize and deserialize an object, they are writeObject(Object) , readObject(). The writeObject method is in the ObjectOutputStream class while the readObject() method is in the ObjectInputStream class. All the instance variables of the object are saved and retrieved successfully as they were saved provided no instance variable is marked with the keyword transient. This keyword if used specifies that the state of that instance variable is not to be saved. 

Following code demonstrates how to do serialization


public class MyClass implements Serialzable
{
     private int i = 10;
     private String name ="ABC";
    
    public int getI(){
            return i;
    }
    public void setI(int i){
        this.i=i;
    }
    public String getName(){

        return name;
    }
    public void setName(String name){
        this.name = name;
   }
}

public class TestSerializable{
  public static void main(String args[])
  {
     MyClass c = new MyClass();
     c.setI(12);
     c.setName("DEF");
     // printing values before saving
     System.out.println("Before saving "+c.getName()+" "+c.getI()) ;
   
     try{
              // Serializing and saving to the file.
              ObjectOutputStream ous = new ObjectOutputStream(new FileOutputStream("datafile.txt"));
              ous.writeObject(c);
              ous.flush();

              // Deserializing the object.
             ObjectInputStream ois = new ObjectInputStream(new FileInputStream("datafile.txt"));
             MyClass c1 = (MyClass) ois.readObject();
          }
          catch(Exception e)
         {
             e.printStackTrace();
           }
     // printing after retrieving the object
     System.out.println("After retrieving "+c1.getName()+" "+c1.getI());     
  }//end of main
} // end of class

The output of this program will be:

Before saving DEF 12
After retrieving DEF 12