Friday 24 February 2012

Deserialization in java


Derialization
   Reading the state of object from a peristance media to our java program is called derialization.

By using FileInputStream and ObjectOutputStream we can achieve deserialization.

Steps to perform Deserialization
1)creation of an object to FileInputStream by sending refence of File Object
2)creatinon of an object to ObjectInputStream by sending refernce of FileInputStream
3)Then calling the readObject() by using refernce of ObjectInputStream
Ex:ois.readObject();
4)readObject() returns an Object class object & hence we have to downcast to desired object
5)calling statements of both the constructors of ObjectInputStream & FileInputStream raise checked type of exception to IOException, where as calling statements of readObject() raise both IOException and ClassNotFoundException
6)There is flusing operation in deserialization.


Java program to demonstrate deserialization.
package com.usr.io;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;

public class DeserializationDemo {
       public static void main(String[] args) {
              Person p = null;
              File file = new File("person.ser");
              FileInputStream fis = null;
              ObjectInputStream ois = null;
              try {
                     fis = new FileInputStream(file);
                     ois = new ObjectInputStream(fis);
                     p = (Person) ois.readObject();
                     System.out.println("Object Deserialized.......");
                     System.out.println("Age:" + p.age);
                     System.out.println("Name:" + p.name);
                     System.out.println("Height:" + p.height);
                     System.out.println("Weight:" + p.weight);
                     System.out.println("password:" + p.password);

              } catch (ClassNotFoundException ex) {
                     System.out.println("Person class not found");
                     ex.printStackTrace();
              } catch (IOException ex) {
                     ex.printStackTrace();
              } finally {
                     try {
                           if (ois != null) {
                                  ois.close();
                           }
                     } catch (IOException ex) {
                           ex.printStackTrace();
                     }
                     try {
                           if (fis != null) {
                                  fis.close();
                           }
                     } catch (IOException ex) {
                           ex.printStackTrace();
                     }
              }
       }
}
OUTPUT 
Object Deserialized.......
Age:26
Name:sachin
Height:170.23
Weight:62.34
password:null