Saturday, 14 March 2015

Serialization

Writing the state of an object in file is called as serialization.
Creating objects by using file contents is called as de-serialization
File output stream is used to write the contents in files, Object output stream is used to write the object data in under laying stream.
File Input Stream is used to read the data from file. Object Input Stream is used to create/read object from under lying stream
If we want to write any object state in file that object should implement Serializable interface
WAP to serialize an object?
public class Cone implements Serializable
{
    private static final long serialVersionUID = 2415959248340837017L;
    private Integer eno;
    private String ename;
    private Double sal;
}
        Cone c = new Cone();
        c.setEno(1);
        c.setEname("Chandra");
        c.setSal(40000D);
        FileOutputStream out = new FileOutputStream("serialization.ser");
        ObjectOutputStream oos = new ObjectOutputStream(out);
        oos.writeObject(c);

WAP to de serialize an object?
public class DeSerialization
{
    private static final Logger LOGGER = LogUtility.getLogger(DeSerialization.class);

    public static void main(String[] args) throws IOException, ClassNotFoundException
    {
        FileInputStream fis = new FileInputStream("serialization.ser");
        ObjectInputStream ois = new ObjectInputStream(fis);
        Cone c = (Cone) ois.readObject();
        LOGGER.info(c.getEno());
        LOGGER.info(c.getEname());
        LOGGER.info(c.getSal());
    }

}

Static variables won't participate in serialization. Some time we have to write the static variables in file then we have to override the read object() and write object() methods.
public class Cone implements Serializable
{
    private static final long serialVersionUID = 2415959248340837017L;
    private Integer eno;
    private String ename;
    private Double sal;
    private static String name;
    //setter and getter methods
    private void writeObject(ObjectOutputStream oos) throws IOException
    {
        oos.writeInt(getEno());
        oos.writeObject(getName());
        oos.writeDouble(getSal());
        oos.writeObject(getName());
    }
   
    private void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException
    {
        setEno(ois.readInt());
        setEname((String)ois.readObject());
        setSal(ois.readDouble());
        setName((String)ois.readObject());
    }
}

Transient:

Some time we can't add instance variables in files. For example password, account number.
To provide these functionality we use the transient key word.


No comments:

Post a Comment