Thursday, September 10, 2015

Java Refresher - Serialization and De-Serialization

Serialization and Deserialization:

Serialization: a mechanism where the object state can be saved as bytes, eg: into a file.

De-Serialization : a mechanism to read out the data from the file or byte, that was serialized.

Advantage: platform independent reads. can be transferred over the network.

The object that is being serialized should be implemented with java.io.Serializable

To simply serialize and deserialize the object we have two class to do it.
                > ObjectOutputStream   - Serialize and writes to a file.
                         public final void writeObject(Object )  => this method converts the object to a file.

                > ObjectInputStream   - De-Serialize and converts to an java object again.
                        public final Object readObject(); => this method converts the byte content to object.


Serialization demo:

/*Class to be serialized*/
public class ObjTOSerialize implements java.io.Serializable{
public String name;
}


/* Serialization code snippet */

public static void main(String [] args)  throws IOException {
    ObjTOSerialize obj = new ObjTOSerialize ();
    obj.name = "Test";
         FileOutputStream fileOut = new FileOutputStream ("/file/ObjSer.txt");
         ObjectOutputStream out = new ObjectOutputStream(fileOut);
         out.writeObject(e);
         out.close();
         fileOut.close();
}

/* De- Serialization code snippet */
public static void main(String args[]) throws IOException, ClassNotFoundException{
            FileInputStream fin = new FileInputStream(new File("/file/ObjSer.txt"));
ObjectInputStream ofin = new ObjectInputStream(fin);
ObjTOSerialize obj= (ObjTOSerialize )ofin.readObject();
System.out.println(obj.name);
ofin.close();
fin.close();
}

Note: if anything is changed to the ObjSer.txt, there will be an exception when de-serializing.

Exception in thread "main" java.io.EOFException
at java.io.ObjectInputStream$PeekInputStream.readFully(Unknown Source)
at java.io.ObjectInputStream$BlockDataInputStream.readUTFBody(Unknown Source)
at java.io.ObjectInputStream$BlockDataInputStream.readUTF(Unknown Source)
at java.io.ObjectInputStream.readString(Unknown Source)
at java.io.ObjectInputStream.readObject0(Unknown Source)









No comments:

Post a Comment