Monday, 26 August 2013

Serialization in java

In java, Serialization is a process used to convert object into the binary format which can be persisted into disk or sent over the network.
So when is Serialization used? Serialization is used when we want to persist the object. It is also used by RMI(Remote Method Invocation) to  pass objects between JVMs.

Java provides Serialization API for serializing and deserializing an object which includes java.io.Serializable, java.io.Externalizable, ObjectInputStream, ObjectOutputStream.

How Serialization is performed in java?
      To persist an object in java, first step is to flatten an object. For that, the respective class should implement the java.io.Serializable interface. We don't need to override any method because the Serializable interface is a marker interface.(Marker interface is a interface that does not have any methods)

class SerializableClass implements java.io.Serializable{
}

Now we marked the object for flattening.

Next Step is to persist the object. To persist the object, we use the java.io.ObjectOutputStream.

class SerializableClass implements java.io.Serializable{
     //Utility to write object into file
     static void saveObject(SerializableClass object){
            FileOutputStream fos = null;
            ObjectOutputStream oos = null;
            
            try{
                    fos = new FileOutputStream("test.ser");
                    oos = new ObjectOutputStream(fos);
                    oos.writeObject(object);  
                    oos.close();
            }catch(IOException e){}
     }
   
      //Utility to read the object from file
      static  SerializableClass readObject(){
               FileInputStream fis = null;
               ObjectInputStream ois= null;
               SerializableClass object = null;
               try{
                       fis = new FileInputStream("test.ser");
                       ois = new ObjectInputStream(fis);
                       object = (SerializableClass)ois.readObject();
                       ois.close();
               }catch(IOException e){}
              return object;
      }   

     public static void main(String... args){
             SerializableClass  object = new SerializableClass ();
             saveObject(object);
     }
}


References:
1. http://docs.oracle.com/javase/6/docs/api/java/io/Serializable.html
2. http://docs.oracle.com/javase/7/docs/platform/serialization/spec/serial-arch.html

No comments:

Post a Comment