JavaData & JavaWorking with Serialization in Java

Working with Serialization in Java

Developer.com content and product recommendations are editorially independent. We may make money when you click on links to our partners. Learn More.

Serialization is the process of converting an object into a linear stream of bytes. This linear stream can be persisted into a persistent storage media or in memory. If the object is persisted in a persistent storage media, the storage medium generally used is a database or a file in the file system. The reverse process is termed deserialization, a process in which the object is re-constructed from the linear stream. In this article, I would like to present how we can work with serialization in Java.

To serialize an object in Java, both these conditions should be satisfied:

  • The class to which the instance belongs to must implement java.io.Serializable.
  • The members of the class should be serializable. If one or more of the members are not to be serialized, they should be marked as transient.

It should be noted that serialization and deserialization is JVM independent; you can serialize an object in one platform and deserialize the object in some other platform. The ObjectInputStream and ObjectOutputStream classes in the Java library provide support for serialization and deserialization. You can use the following writeObject method of the ObjectOutputStream class to serialize an object and send it to the output stream.

public final void writeObject(Object x) throws IOException

To deserialize the previously serialized instance, you can use the readObject method of the ObjectInputStream class.

public final Object readObject() throws IOException,
   ClassNotFoundException

Implementing Serialization in Java

Let’s now create a simple application to demonstrate how serialization and deserialization work in Java. To begin with, you should have a class that implements java.io.Serializable. This class would be used to store the data that you would want to be serialized. Unless your class is marked serializable by implementing java.io.Serializable, you cannot serialize its instance. Here’s how our entity class called Author looks.

public class Author implements java.io.Serializable
{
   public String firstName;
   public String lastName;
   public String address;
}

Now, to serialize an instance of the Author class declared above, you can use the method given next.

public static void Serialize(Object obj)
{
   try
   {
      FileOutputStream fileOut =
         new FileOutputStream("F:test.ser");
      ObjectOutputStream out =
         new ObjectOutputStream(fileOut);
      out.writeObject(obj);
      out.close();
      fileOut.close();
   }
   catch(IOException i)
   {
      i.printStackTrace();
      return;
   }
}

As you can see in the preceding Serialize method, an instance of FileOutputStream is created and then it is assigned to the constructor of ObjectOutputStream when instantiating the latter. Next, the writeObject method is called with the instance of ObjectOutputStream as parameter. You should then close both the ObjectOutputStream and FileOutputStream instances.

After an object is serialized and stored in a file, you also can deserialize the object from the stream at a later point in time. The following method shows how the serialized object can be deserialized. To deserialize an object, you need to use FileInputStream to read the stream of bytes. Next, you should create an instance of ObjectInputStream and pass the instance of FileInputStream class when instantiating. This instance of ObjectInputStream is used to read back the serialized object from the stream of bytes. Once you are done deserializing the object, you should close both the instances of FileInputStream and ObjectInputStream.

public static Object DeSerialize()
{
   Object obj = null;
   try
   {
      FileInputStream fileIn =
         new FileInputStream("F:test.ser");
      ObjectInputStream in =
         new ObjectInputStream(fileIn);
      obj = in.readObject();
      in.close();
      fileIn.close();
   }
   catch(IOException i)
   {
      i.printStackTrace();
      return null;
   }
   catch(ClassNotFoundException c)
   {
      c.printStackTrace();
      return null;
   }
   return obj;
}

You should catch the ClassNotFoundException in one of your catch blocks as shown in the preceding code snippet because the JVM would throw this exception if the byte code for this class is not found at the time of deserializing an object.

The following code snippet illustrates how you can invoke the Serialize and DeSerialize methods.

public static void main(String[] args) {
   Author author = new Author();
   author.firstName = "Joydip";
   author.lastName = "Kanjilal";
   author.address = "Tarasankar Sarani,
      	P.O. Belgachia, Kolkata";
   Serialize(author);
   Author deserializedAuthorInstance =
      (Author)DeSerialize();
   System.out.println("nDeserialized Author
      instance...");
   System.out.println("First Name: " +
      deserializedAuthorInstance.firstName);
   System.out.println("Last Name: " +
      deserializedAuthorInstance.lastName);
   System.out.println("Address: " +
      deserializedAuthorInstance.address);
}

Summary

The Java Programming language provides excellent support for serializing and deserializing instances to persistent or non-persistent storage media. In this article, we have had a bird’s eye view of serialization in Java. Happy reading!

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Latest Posts

Related Stories