Pages

Friday, 27 July 2012

Serialization in Java

Serialization is a process of writing the state of an object to disk in the form of file. 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 program. But when we use serialization, the few points we should keep in mind,

  1. Only that object of class can be serialized which impliments  java.io.Serializable interface.      
  2.  In the process of serialization all member of the class has been serialiazed. If we want to prevent serialization of any member from a class we need to declare it transient. It is a special keyword in java which is used to prevent serialization of member.
  3. static members of the class has not been serialized. A member class(A class which defined inside a class as a member of  outer class) which if declared static can not be serialized. 
  4. In java, array of any type can be also serialized because java treated array as an object.
  5. Primitive data types can not be serialized.

How do we use serialization?

There are two high-level classed which is used to perform serialization, ObjectInputStream and ObjectOutputStream.

The ObjectOutputStream class contains many write methods for writing objects into streams, but one method in particular important that we will use in our example :
public final void writeObject(Object x) throws IOException
 
The ObjectInputStream class contains read method for reading objects from stream, one of them is show here,
 public final Object readObject() throws IOException,
ClassNotFoundException 
 
The return type of this method is Object so we will need to cast it to its appropriate data type.
 
Example of Serialization:- 
 

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

/**
 * @author Saurav Gupta
 *
 */

public class SerializationTest {
 public static void main(String[] s) {
  String str = "Hello Java";
  try {
    FileOutputStream fOut= new FileOutputStream("data.ser");
    ObjectOutputStream outStream = new ObjectOutputStream(fOut);

           outStream.writeObject(str);
           outStream.close();

        } catch (Exception e) {
           e.printStackTrace();
        }
    }
}
 
Example of Deserialization:- 
 
import java.io.FileInputStream;
import java.io.ObjectInputStream;

/**
 * @author Saurav Gupta
 * 
 */

public class DeserializationTest {
  public static void main(String[] s) {
    try {
        FileInputStream fIn = new FileInputStream("data.ser");
        ObjectInputStream inStream = new ObjectInputStream(fIn);

        String str = (String) inputStream.readObject();
        System.out.println(str);

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

 
 

No comments:

Post a Comment