October 22, 2014
Hot Topics:
RSS RSS feed Download our iPhone app

Java Serialization: Persist Your Objects

  • February 8, 2010
  • By Sridhar M S
  • Send Email »
  • More Articles »

When a Java application is executed, a large number of objects are created. Most of these objects are created and destroyed in the runtime. It would be convenient if Java saved these objects for future use or recreated them from an existing source and then used them—even when the application is re-run after it was stopped. The good news is Java does support this mechanism with the Java Serialization API.

Serialization is the process of saving an object's state to a persistence store and also rebuilding the object from the saved information when needed in the future. With Serialization, you can serialize (persist) any object that you don't need or that may have been used in some other application or may be used later.

Understanding the Java Serialization API

Any Java object can be a candidate for serialization; it simply needs to implement the Serializable interface. This interface is a marker interface with no default implementation. The interface is an indication to the Java runtime that the object is valid for persistence.

The method writeObject(...) of the ObjectOutputStream class makes the serialization transparent to the developer. You don't need to worry about creating the persistent file, reading the end-of-file, creating a new file, etc., thereby relieving you of a lot of additional effort.

As an example, here is a DataAndTimeObject class that can be serialized:

import java.io.Serializable;
import java.util.*;
 
//This class represents DataAndTimeObject that can be serialized
public class DateAndTimeObject implements Serializable
{
   private Date dateAndTime;
 
   public DateAndTimeObject()
   {
      dateAndTime = Calendar.getInstance().getTime();
   }
 
   public Date getDateAndTime()
   {
      return dateAndTime;
   }
}


The difference between the above object and a non-serializable object is that this one implements the Serializable interface.

The following code shows how you would serialize the object DataAndTimeObject.

import java.io.*;
 
//This class provides methods to serialize a serializable object
public class SerializeObject
{
   public static void main(String args[])
   {
      String serializeFileName = "dateAndTime.ser";
      if(args.length > 0)
      {
         serializeFileName = args[0];
      }
 
      DateAndTimeObject dateAndTimeObject = new DateAndTimeObject();
      FileOutputStream fileOutputStream = null;
      ObjectOutputStream objectOutputStream = null;
 
      try
      {
         fileOutputStream = new FileOutputStream(serializeFileName);
         objectOutputStream = new ObjectOutputStream(fileOutputStream);
         //The object is being persisted here
         objectOutputStream.writeObject(dateAndTimeObject);
         objectOutputStream.close();
         System.out.println("Serialize Date and Time   : " + dateAndTimeObject.getDateAndTime());
         System.out.println("Object serialized in file : " + serializeFileName);
      }
      catch(IOException ioe)
      {
         //Close all I/O streams
         ioe.printStackTrace();
         //Handle the exception here
      }
   }
}


Here is the output from the above code.

The class SerializeObject has an implementation that can serialize the object DataAndTimeObject. This implementation also takes an argument for the serialize object file name, ignoring whether or not the file name would be dateAndTime.ser. The writeObject(...) method of the ObjectOutputStream class facilitates the serialization process. As discussed previously, the I/O streams take care of the file-handling overhead.

Here is the code for creating the object from the file dateAndTime.ser.

import java.io.*;
import java.util.Calendar;
 
public class DeSerializeObject
{
   public static void main(String args[])
   {
      DateAndTimeObject dateAndTimeObject = null;
      FileInputStream fileInputStream = null;
      ObjectInputStream objectInputStream = null;
 
      String serializedFileName = "dateAndTime.ser";
      if(args.length > 0)
      {
         serializedFileName = args[0];
      }
 
      try
      {
         fileInputStream = new FileInputStream(serializedFileName);
         objectInputStream = new ObjectInputStream(fileInputStream);
         dateAndTimeObject = (DateAndTimeObject) objectInputStream.readObject();
         objectInputStream.close();
 
         //Date and Time that was serialized
         System.out.println("Serialize Date and Time: " + dateAndTimeObject.getDateAndTime());
         //Current Date and Time
         System.out.println("Current Date and Time  : " + Calendar.getInstance().getTime());
 
      }
      catch(FileNotFoundException fnfe)
      {
         System.out.println("File not found: "+fnfe.getMessage());
         //Close all I/O streams
         //Handle the exception here
      }
      catch(IOException ioe)
      {
         ioe.printStackTrace();
         //Close all I/O streams
         //Handle the exception here
      }
      catch(ClassNotFoundException cnfe)
      {
         cnfe.printStackTrace();
         //Close all I/O streams
         //Handle the exception here
      }
   }
}


Here is the output from the above listing.

The readObject(...) method of the ObjectInputStream class facilitates creating the object in the runtime from the serialized object.


Tags: Java, Serialization, Persistence, Java Object



Page 1 of 2



Comment and Contribute

 


(Maximum characters: 1200). You have characters left.

 

 


Sitemap | Contact Us

Rocket Fuel