May 2004 Technical Tip – Object Persistence in Java

When a class is instantiated in a Java program, the resultant object is said to be volatile; that is, it will go away when the program ends. Object persistence is the process of saving an object to storage, and the simplest means of doing so is to use object serialization.

According to the API, "Serializability of a class is enabled by the class implementing the java.io.Serializable interface. Classes that do not implement this interface will not have any of their state serialized or deserialized. All subtypes of a serializable class are themselves serializable. The serialization interface has no methods or fields and serves only to identify the semantics of being serializable."

So all that is necessary for a class to be serializable is to implement the Serializable interface, which has no methods. We will demonstrate the entire process here. We begin by creating a simple class called, appropriately, SimplePoint, which models an (x,y) point in the Cartesian plane.

import java.io.Serializable;

public class SimplePoint implements Serializable
{
    private int x;
    private int y;

    public SimplePoint(int x, int y)
    {
        this.x = x;
        this.y = y;
    }

    public String toString()
    {
        return "(" + x + "," + y + ")";
    }
}  // end SimplePoint class
Download source code here.

Next, we create a simple application called WriteSimplePoint which instantiates a SimplePoint and writes that object to the C drive. Note the writeObject method of the ObjectOutputStream class can throw IOException (which I chose to throw back to the main method.)

import java.io.*;

public class WriteSimplePoint
{
    public static final String FILE_NAME =
        new String("c:/SimplePoint.ser");

    public static void main(String[] args)
        throws IOException
    {
        SimplePoint p = new SimplePoint(11,8);
        ObjectOutputStream out = new ObjectOutputStream(
            new FileOutputStream(FILE_NAME));
        out.writeObject(p);
        out.close();
        System.out.println("Point " + p + " written to " + FILE_NAME);
       System.out.println("Done.");
    }
}  // end WriteSimplePoint class
Download source code here.

Output is:

C:\Java\MyJava>java WriteSimplePoint
Point (11,8) written to c:/SimplePoint.ser
Done.

Finally, we create a simple application called ReadSimplePoint which reads the object from the C drive. Note that the readObject method (1) can throw ClassNotFoundException and therefore requires a try/catch, and (2) returns an instance of Object which must then be cast to the desired class (SimplePoint in this case.)

import java.io.*;

public class ReadSimplePoint
{
    public static final String FILE_NAME = 
        new String("c:/SimplePoint.ser");

    public static void main(String[] args)
        throws IOException
    {
        SimplePoint p = null;
        try
        {
            ObjectInputStream in = new ObjectInputStream(
                new FileInputStream(FILE_NAME));
            p = (SimplePoint)in.readObject();
            in.close();
            System.out.println("Point " + p + " read from " + FILE_NAME);
        }
        catch (ClassNotFoundException cnfe)
        {
            p = null;
            System.out.println("Error reading point from " + FILE_NAME);
        }
        System.out.println("Done.");
    }
}  // end ReadSimplePoint class
Download source code here.

Output is:

C:\Java\MyJava>java ReadSimplePoint
Point (11,8) read from c:/SimplePoint.ser
Done.

The complete source for these examples can be found at http://www.caliberdt.com/tips. If you like concise but complete examples as shown in this article, then you’ll love our courses! We hope you’ll consider Caliber Data Training when you are looking for a Java training provider.


Go to the articles index. Written by Bill Qualls. Copyright © 2004 by Caliber Data Training 800.938.1222