How to Serialize and Deserialize object in Java?

UPDATED: 13 April 2015

javadoc
To serialize an object means to convert its state to a byte stream so way that the byte stream can be reverted back into a copy of the object. A Java object is serializable if its class or any of its superclasses implements either the java.io.Serializable interface or its subinterface, java.io.Externalizable.

Deserialization is the process of converting the serialized form of an object back into a copy of the object.

Source Code (User.java)
Any object that implements Serializable interface is eligible for Object Serialization.
import java.io.Serializable;

public class User implements Serializable{
    private transient long id;
    private String Firstname;
    private transient String Lastname;
    private transient boolean status;

    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

    public String getFirstname() {
        return Firstname;
    }

    public void setFirstname(String Firstname) {
        this.Firstname = Firstname;
    }

    public String getLastname() {
        return Lastname;
    }

    public void setLastname(String Lastname) {
        this.Lastname = Lastname;
    }
    
    public boolean isStatus() {
        return status;
    }

    public void setStatus(boolean status) {
        this.status = status;
    }
}

transient keyword
Any variable or object declared with transient keyword will not be stored in Serialize Object. It will give you default value particular data type.
  • Boolean Data type: transient boolean will give false value in Object Deserialization.
  • Numeric Data types: transient int, double, long, float will give 0 value in Object Deserialization.
  • String Data type: transient String will give null value in Object Deserialization.
  • Any Object: transient ANY_OBJECT will give null value in Object Deserialization.

Source Code (SerializeObject.java)
import java.io.File;
import java.io.FileOutputStream;
import java.io.ObjectOutputStream;

public class SerializeObject {
    public static void main(String[] args) {
        System.out.println("Object Serialization Code...");
        /* Creating an object of User */
        User objUser = new User();
        
        /* Set properties of User object */
        /* Id will be set to `0` in serialized object because it is declared as `transient` */
        objUser.setId(111l);
        /* Set Firstname */
        objUser.setFirstname("Vicky");
        /* Lastname will be set to `null` in serialized object because it is declared as `transient` */
        objUser.setLastname("Thakor");
        /* Status will be set to `false` in serialized object because it is declared as `transient` */
        objUser.setStatus(true);
        
        /**
         * try(resource)...catch is supported on Java 7 or above.
         * We don't have to explicitly close the resource. 
         * You can follow same code with closing resources in `finally`.
         */
        try(
                /* Create object of FileOutputStream to store object in file [Windows: C:\Users\CurrentUser\User.ser(i.e: `.ser` Standard File Extension)] */
                FileOutputStream objFileOutputStream = new FileOutputStream(System.getProperty("user.home") + File.separatorChar + "User.ser");
                /* Create object of ObjectOutputStream to write objUser on file. */
                ObjectOutputStream objObjectOutputStream = new ObjectOutputStream(objFileOutputStream);
            ){
            /* Write object on file. */
            objObjectOutputStream.writeObject(objUser);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}

Source Code (DeSerializeObject)
import java.io.File;
import java.io.FileInputStream;
import java.io.ObjectInputStream;

public class DeSerializeObject {
    public static void main(String[] args) {
        System.out.println("Object Deserialization Code...");
        /**
         * try(resource)...catch is supported on Java 7 or above.
         * We don't have to explicitly close the resource. 
         * You can follow same code with closing resources in `finally`.
         */
        try(
                /* Create object of FileInputStream to get serialized file. */
                FileInputStream objFileInputStream = new FileInputStream(System.getProperty("user.home") + File.separatorChar + "User.ser");
                /* Create object of ObjectInputStream to read User object from file. */
                ObjectInputStream objObjectInputStream = new ObjectInputStream(objFileInputStream);
           ){
            /* Read the User object from file. We've to cast it to our object */
            User objUser = (User) objObjectInputStream.readObject();
            /* Print the properties of User object */
            System.out.println(objUser.getId());
            System.out.println(objUser.getFirstname());
            System.out.println(objUser.getLastname());
            System.out.println(objUser.isStatus());
        }catch(Exception ex){
            ex.printStackTrace();
        }
    }
}

Output (DeSerializeObject.java)
Object Deserialization Code...
0
Vicky
null
false

0 comments :