Serialization in java


Click here to download eclipse supported ZIP file



Java provides a mechanism, called object serialization where an object can be represented as a sequence of bytes that includes the object's data as well as information about the object's type and the types of data stored in the object.

After a serialized object has been written into a file, it can be read from the file and deserialized that is, the type information and bytes that represent the object and its data can be used to recreate the object in memory.

Most impressive is that the entire process is JVM independent, meaning an object can be serialized on one platform and deserialized on an entirely different platform.

Classes ObjectInputStream and ObjectOutputStream are high-level streams that contain the methods for serializing and deserializing an object.

The ObjectOutputStream class contains many write methods for writing various data types, but one method in particular stands out:

public final void writeObject(Object x) throws IOException

The above method serializes an Object and sends it to the output stream. Similarly, the ObjectInputStream class contains the following method for deserializing an object:

public final Object readObject() throws IOException, ClassNotFoundException

This method retrieves the next Object out of the stream and deserializes it. The return value is Object, so you will need to cast it to its appropriate data type.

To demonstrate how serialization works in Java, I am going to use the Employee class that we discussed early on in the book. Suppose that we have the following Employee class, which implements the Serializable interface:



 

    
package com.cv.java.serialization;

public class Employee implements java.io.Serializable {
  public String name;
  public String address;
  public transient int SSN;
  public int number;

  public void mailCheck() {
    System.out.println("Mailing a check to " + name + " " + address);
  }
}

Notice that for a class to be serialized successfully, two conditions must be met:

  • The class must implement the java.io.Serializable interface.

  • All of the fields in the class must be serializable. If a field is not serializable, it must be marked transient.

If you are curious to know if a Java Standard Class is serializable or not, check the documentation for the class. The test is simple: If the class implements java.io.Serializable, then it is serializable; otherwise, it's not.

Serializing an Object:

The ObjectOutputStream class is used to serialize an Object. The following SerializeDemo program instantiates an Employee object and serializes it to a file.

When the program is done executing, a file named employee.ser is created. The program does not generate any output, but study the code and try to determine what the program is doing.

Note: When serializing an object to a file, the standard convention in Java is to give the file a .ser extension.



 

    
package com.cv.java.serialization;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;


public class SerializeDemo
{
   public static void main(String [] args)
   {
      Employee e = new Employee();
      e.name = "Reyan Ali";
      e.address = "Phokka Kuan, Ambehta Peer";
      e.SSN = 11122333;
      e.number = 101;
      
      try
      {
         FileOutputStream fileOut =
         new FileOutputStream("/tmp/employee.ser");
         ObjectOutputStream out = new ObjectOutputStream(fileOut);
         out.writeObject(e);
         out.close();
         fileOut.close();
         System.out.printf("Serialized data is saved in /tmp/employee.ser");
      }catch(IOException i)
      {
          i.printStackTrace();
      }
   }
}

Deserializing an Object:

The following DeserializeDemo program deserializes the Employee object created in the SerializeDemo program. Study the program and try to determine its output:



 

    
package com.cv.java.serialization;

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

public class DeserializeDemo
{
   public static void main(String [] args)
   {
      Employee e = null;
      try
      {
         FileInputStream fileIn = new FileInputStream("/tmp/employee.ser");
         ObjectInputStream in = new ObjectInputStream(fileIn);
         e = (Employeein.readObject();
         in.close();
         fileIn.close();
      }catch(IOException i)
      {
         i.printStackTrace();
         return;
      }catch(ClassNotFoundException c)
      {
         System.out.println("Employee class not found");
         c.printStackTrace();
         return;
      }
      System.out.println("Deserialized Employee...");
      System.out.println("Name: " + e.name);
      System.out.println("Address: " + e.address);
      System.out.println("SSN: " + e.SSN);
      System.out.println("Number: " + e.number);
    }
}

This would produce the following result:

Deserialized Employee...
Name: Reyan Ali
Address:Phokka Kuan, Ambehta Peer
SSN: 0
Number:101

Here are following important points to be noted:

  • The try/catch block tries to catch a ClassNotFoundException, which is declared by the readObject() method. For a JVM to be able to deserialize an object, it must be able to find the bytecode for the class. If the JVM can't find a class during the deserialization of an object, it throws a ClassNotFoundException.

  • Notice that the return value of readObject() is cast to an Employee reference.

  • The value of the SSN field was 11122333 when the object was serialized, but because the field is transient, this value was not sent to the output stream. The SSN field of the deserialized Employee object is 0.


Examples for serialization :

 

    
package com.cv.java.serialization;

import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

/**
 @author Chandra Vardhan
 
 */
public class Account implements Serializable {
  String username = "chandra";
  transient String password = "vardhan";
  transient int pin = 345;

  private void writeObject(ObjectOutputStream osthrows Exception {
    os.defaultWriteObject();
    String epassword = "123" + password;
    os.writeObject(epassword);
    int epin = pin + 444;
    os.writeObject(epin);
  }

  private void readObject(ObjectInputStream inthrows Exception {
    in.defaultReadObject();
    String epassword = (Stringin.readObject();
    password = epassword.substring(3);
    int epin = (Integerin.readObject();
    pin = epin - 444;
  }

}


 

    
package com.cv.java.serialization;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

/**
 @author Chandra Vardhan
 
 */
public class AccountTest {
  public static void main(String[] args) {
    ObjectOutputStream oos = null;
    FileOutputStream fos = null;
    ObjectInputStream ois = null;
    FileInputStream fis = null;
    try {
      Account a1 = new Account();
      System.out.println(a1.username + " ............." + a1.password);
      fos = new FileOutputStream("Account.txt");
      oos = new ObjectOutputStream(fos);
      oos.writeObject(a1);
      fis = new FileInputStream("Account.txt");
      ois = new ObjectInputStream(fis);
      Account a2 = (Accountois.readObject();
      System.out.println(a2.username + " ............." + a2.password);
    catch (FileNotFoundException e) {
      e.printStackTrace();
    catch (IOException e) {
      e.printStackTrace();
    catch (ClassNotFoundException e) {
      e.printStackTrace();
    finally {

      try {
        if (oos != null)
          oos.close();
        if (fos != null)
          fos.close();
        if (fis != null)
          fis.close();
        if (ois != null)
          ois.close();
      catch (IOException e) {
        e.printStackTrace();
      }

    }

  }
}


 

    
package com.cv.java.serialization;

/**
 @author Chandra Vardhan
 
 */
public class Animal {
  int i = 10;
}


 

    
package com.cv.java.serialization;

import java.io.Serializable;


/**
 @author Chandra Vardhan
 
 */
public class Cat implements Serializable{
  Rat r=new Rat();

}


 

    
package com.cv.java.serialization;

import java.io.Serializable;

/**
 @author Chandra Vardhan
 
 */
public class Dog implements Serializable{
  public static final int j = 10;
  public static final int i = 20;
  Cat c=new Cat();
}


 

    
package com.cv.java.serialization;

import java.io.Serializable;


/**
 @author Chandra Vardhan
 
 */
public class Dog1 implements Serializable {
  int i =10;
  int j =20;
}


 

    
package com.cv.java.serialization;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

//import java.io.Serializable;

/**
 @author Chandra Vardhan
 
 */
public class DogSerializableTest {
  public static void main(String[] argsthrows Exception {
    ObjectOutputStream oos = null;
    FileOutputStream fos = null;
    ObjectInputStream ois = null;
    FileInputStream fis = null;
    try {
      Dog d1 = new Dog();
      fos = new FileOutputStream("Dog.txt");
      oos = new ObjectOutputStream(fos);
      oos.writeObject(d1);
      fis = new FileInputStream("Dog.txt");
      ois = new ObjectInputStream(fis);
      Dog d2 = (Dogois.readObject();
      System.out.println(d2.c.r.j);
    catch (FileNotFoundException e) {
      e.printStackTrace();
    catch (IOException e) {
      e.printStackTrace();
    catch (ClassNotFoundException e) {
      e.printStackTrace();
    finally {

      try {
        if (oos != null)
          oos.close();
        if (fos != null)
          fos.close();
        if (fis != null)
          fis.close();
        if (ois != null)
          ois.close();
      catch (IOException e) {
        e.printStackTrace();
      }

    }

  }

}


 

    
package com.cv.java.serialization;

import java.io.Externalizable;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;

/**
 @author Chandra Vardhan
 
 */
public class ExternalizablePair implements Externalizable {
  private String key;
  private String value;

  public ExternalizablePair() {
    System.out.println("no arg constructors");
  }

  public ExternalizablePair(String key, String value) {
    this.key = key;
    this.value = value;
  }

  public String toString() {
    return "pair";
  }

  @Override
  public void writeExternal(ObjectOutput outthrows IOException {
    out.writeObject(key);
    out.writeObject(value);
  }

  @Override
  public void readExternal(ObjectInput inthrows IOException, ClassNotFoundException {
    String key = (Stringin.readObject();
    System.out.println(key);
    String value = (Stringin.readObject();
    System.out.println(value);
  }

  public String getKey() {
    return key;
  }

  public void setKey(String key) {
    this.key = key;
  }

  public String getValue() {
    return value;
  }

  public void setValue(String value) {
    this.value = value;
  }
  
  

}


 

    
package com.cv.java.serialization;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

/**
 @author Chandra Vardhan
 
 */
public class ExternalizablePairTest {
  public static void main(String[] args) {

    ObjectOutputStream oos = null;
    FileOutputStream fos = null;
    ObjectInputStream ois = null;
    FileInputStream fis = null;
    try {
      ExternalizablePair pair = new ExternalizablePair("hello""world");
      System.out.println("initially" + pair.toString());
      fos = new FileOutputStream("ExternalizablePair.txt");
      oos = new ObjectOutputStream(fos);
      pair.writeExternal(oos);
      oos.writeObject(pair);
      oos.flush();
      oos.writeObject(pair);
      ExternalizablePair pair2 = new ExternalizablePair();
      fis = new FileInputStream("ExternalizablePair.txt");
      ois = new ObjectInputStream(fis);
      pair2.readExternal(ois);
      ois.readObject();
      System.out.println(pair.getKey() "========" + pair.getValue());
    catch (FileNotFoundException e) {
      e.printStackTrace();
    catch (IOException e) {
      e.printStackTrace();
    catch (ClassNotFoundException e) {
      e.printStackTrace();
    finally {

      try {
        if (oos != null)
          oos.close();
        if (fos != null)
          fos.close();
        if (fis != null)
          fis.close();
        if (ois != null)
          ois.close();
      catch (IOException e) {
        e.printStackTrace();
      }

    }
  }

}


 

    
package com.cv.java.serialization;

import java.io.Serializable;

/**
 @author Chandra Vardhan
 
 */
public class Rat implements Serializable {
  int j=10;
}


 

    
package com.cv.java.serialization;

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

/**
 @author Chandra Vardhan
 
 */
public class Receiver {

  public static void main(String[] argsthrows Exception {

    ObjectInputStream ois = null;
    FileInputStream fis = null;
    try {
      fis = new FileInputStream("Account.txt");
      ois = new ObjectInputStream(fis);
      Dog1 a2 = (Dog1ois.readObject();
      System.out.println(a2.i + " ............." + a2.j);
    catch (FileNotFoundException e) {
      e.printStackTrace();
    catch (IOException e) {
      e.printStackTrace();
    catch (ClassNotFoundException e) {
      e.printStackTrace();
    finally {

      try {

        if (fis != null)
          fis.close();
        if (ois != null)
          ois.close();
      catch (IOException e) {
        e.printStackTrace();
      }

    }

  }

}


 

    
package com.cv.java.serialization;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;

public class Sender {

  public static void main(String[] argsthrows Exception {

    ObjectOutputStream oos = null;
    FileOutputStream fos = null;

    try {
      Dog1 a1 = new Dog1();
      System.out.println(a1.i + " ............." + a1.j);
      fos = new FileOutputStream("Account.txt");
      oos = new ObjectOutputStream(fos);
      oos.writeObject(a1);
      System.out.println("serialization successful");

    catch (FileNotFoundException e) {
      e.printStackTrace();
    catch (IOException e) {
      e.printStackTrace();
    finally {

      try {
        if (oos != null)
          oos.close();
        if (fos != null)
          fos.close();

      catch (IOException e) {
        e.printStackTrace();
      }

    }

  }

}


 

    
package com.cv.java.serialization;

import java.io.Serializable;

public class SerializablePair implements Serializable {

  private String key;

  private String value;

  public SerializablePair(String key, String value) {

    this.key = key;

    this.value = value;

  }

  @Override
  public String toString() {

    return "Pair ";

  }

  public String getKey() {
    return key;
  }

  public void setKey(String key) {
    this.key = key;
  }

  public String getValue() {
    return value;
  }

  public void setValue(String value) {
    this.value = value;
  }

}


 

    
package com.cv.java.serialization;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class SerializablePairTest {

  private final static String OUTPUT_FILE = "SerializablePair";

  public static void main(String[] args) {
    ObjectOutputStream oos = null;
    FileOutputStream fos = null;
    ObjectInputStream ois = null;
    FileInputStream fis = null;
    try {
      SerializablePair pair = new SerializablePair("Hello""World");

      System.out.println("Initially: " + pair.toString());

      // Serialize the pair to a file.

      fos = new FileOutputStream(OUTPUT_FILE);

      oos = new ObjectOutputStream(fos);

      oos.writeObject(pair);

      // Close all resources.

      oos.flush();

      // Read the contents from the file and create a new instance.

      SerializablePair copyOfPair = null;

      fis = new FileInputStream(OUTPUT_FILE);

      ois = new ObjectInputStream(fis);

      copyOfPair = (SerializablePairois.readObject();

      System.out.println("After de-serialization: " + copyOfPair.toString());
    catch (FileNotFoundException e) {
      e.printStackTrace();
    catch (IOException e) {
      e.printStackTrace();
    catch (ClassNotFoundException e) {
      e.printStackTrace();
    finally {

      try {
        if (oos != null)
          oos.close();
        if (fos != null)
          fos.close();
        if (fis != null)
          fis.close();
        if (ois != null)
          ois.close();
      catch (IOException e) {
        e.printStackTrace();
      }

    }
  }
}


 

    
package com.cv.java.serialization;

import java.io.Externalizable;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;


/**
 @author Chandra Vardhan
 
 */
public class User implements Externalizable{
  int id;
  String username;
  String mailid;
  public User()
  {
    
  }
  public int getId()
  {
    return id;
    
  }
  public String getUsername()
  {
    return username;
  }
  public String getmailid()
  {
    return mailid;
  }
  @Override
  public void writeExternal(ObjectOutput outthrows IOException {
    out.writeObject(id);
    out.writeObject(username);
    out.writeObject(mailid);
  }
  @Override
  public void readExternal(ObjectInput inthrows IOException,
      ClassNotFoundException {
    id=in.readInt();
    username=(Stringin.readObject();
    mailid=(String)in.readObject();
    
  }

}

No comments:

Post a Comment