HomeDigital EditionSys-Con RadioSearch Java Cd
Advanced Java AWT Book Reviews/Excerpts Client Server Corba Editorials Embedded Java Enterprise Java IDE's Industry Watch Integration Interviews Java Applet Java & Databases Java & Web Services Java Fundamentals Java Native Interface Java Servlets Java Beans J2ME Libraries .NET Object Orientation Observations/IMHO Product Reviews Scalability & Performance Security Server Side Source Code Straight Talking Swing Threads Using Java with others Wireless XML
 

"Java Object Serialization for Performance"
Vol. 9, Issue 10, p. 49

	



Listing 1

package com.cathail.serialization;

import java.io.File;
import java.io.ObjectOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.Serializable;
import java.io.NotSerializableException;
import java.io.FileNotFoundException;

/**
 * <p>Title: SerializableObject.java </p>
 * <p>Description: a demonstration of serialization </p>
 * <p>Copyright: The Cathail Group, Copyright (c) 2003</p>
 * <p>Company: The Cathail Group, www.mockbase.org </p>
 * @author John Cahill
 * @version 1.0
 */


public abstract class SerializableObject  implements Serializable
{
    private String pathToSerializeTo = null;

    /**
     *  a basic, no frills serialization method. Note that
     *  it is customary to use ".ser" as a file extension
     *  for the serialized object filename
     *
     */
    public void serialize()
    {
        ObjectOutputStream os = null;

        try
        {
            /* set the output path for the object, if one has been provided...
                 if one has not been provided, just go without it...
             */
            String outPath = ((this.pathToSerializeTo == null) ?
                               this.getClass().getName() :
                                  this.pathToSerializeTo +
                                  File.separatorChar +
                                  this.getClass().getName());

            File serializedObjectFile = new File(outPath + ".ser");

            os = new ObjectOutputStream(new
			 FileOutputStream(serializedObjectFile));

            /*
               also, you can encrypt the bytes coming off
               of the stream for added security!
             */

            os.writeObject(this);
        }
        catch (NotSerializableException ex)
        {
            /* it is important to catch this exception, rather
             * than just catching IOException, because even though
             * this base class implements Serializable, it is possible
             * to construct an object graph that contains non-Serializable
             * objects, which would cause us some problems...
             */
            ex.printStackTrace();
        }
        catch (FileNotFoundException ex)
        {
            ex.printStackTrace();
        }
        catch (IOException ex)
        {
            ex.printStackTrace();
        }
        finally
        {
            try
            {
                if (os != null)
                {
                    os.close();
                }
            }
            catch (IOException ex)
            {
                ex.printStackTrace();
            }
        }
    }

    /** this method will set the output path so that
      *   when serialization takes place, the output will go to
      *   a specific directory.
      *
      * @param path - the path to the serialized output
      */
    public void setSerializationPath(String path)
    {
        this.pathToSerializeTo = path;
    }

}

Listing 2

package com.cathail.serialization;

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

/**
 * <p>Title: DeSerializer.java </p>
 * <p>Description: a demonstration of deserialization </p>
 * <p>Copyright: The Cathail Group, Copyright (c) 2003</p>
 * <p>Company: The Cathail Group, www.mockbase.org </p>
 * @author John Cahill
 * @version 1.0
 */

public class DeSerializer
{
    /**
     * A useful method if your derived class is a factory and controls
     * instances of serialized classes. That way, the factory can locate
     * the ".ser" file and serve up an instance of the reconstituted class.
     *
     * @param objectName - the name of the object to deserialize.
     */
    public static Object deserialize(String objectName)
    {
        Object obj = null;
        ObjectInputStream is = null;

        try
        {
            File serializedObjectFile = new File(objectName + ".ser");

            /* we could delegate the seond half of the deserialization activity
			to our other function, which takes an InputStream as an argument,
			but I don't want to complicate this example...
            */

is = new ObjectInputStream(new FileInputStream(serializedObjectFile));

            obj = is.readObject();
        }
        catch (IOException ex)
        {
            ex.printStackTrace();
        }
        catch (ClassNotFoundException ex1)
        {
            ex1.printStackTrace();
        }
        finally
        {
            try
            {
                if (is != null)
                {
                    is.close();
                }
            }
            catch (IOException ex)
            {
                ex.printStackTrace();
            }
        }

        return obj;
    }

    /*
     *    Alternately, we can provide a method that works with an InputStream
     *    provided by the client. This is important if we are dealing with
     *    different types of InputStreams (File, ByteArray, etc).
     *
     *     @param isStrem - the InputStream to use
     */
    public static Object deserialize(InputStream isStream)
    {
        Object obj = null;
        ObjectInputStream is = null;

        try
        {
            is = new ObjectInputStream(isStream);

            obj = is.readObject();
        }
        catch (IOException ex)
        {
            ex.printStackTrace();
        }
        catch (ClassNotFoundException ex1)
        {
            ex1.printStackTrace();
        }
        finally
        {
            try
            {
                if (is != null)
                {
                    is.close();
                }
            }
            catch (IOException ex)
            {
                ex.printStackTrace();
            }
        }

        return obj;
    }


}

Listing 3

package com.cathail.serialization;

import java.io.File;
import java.io.FileInputStream;
import com.cathail.serialization.tests.TestObject;

/**
 * <p>Title: SerializationFactory.java </p>
 *
 * <pre>
 * Description: a demonstration of a simple Object factory
 *              which utilizes serializable objects
 * </pre>
 *
 * <p>Copyright: The Cathail Group, Copyright (c) 2003</p>
 * <p>Company: The Cathail Group, www.mockbase.org </p>
 * @author John Cahill
 * @version 1.0
 */


public class SerializationFactory
{
    private static SerializationFactory instance = new SerializationFactory();
    private TestObject object = null;

    private SerializationFactory(){}

    /** our "factory" is a singleton so that we can effectively
      * control access to the serialazable object.
      */
    public static SerializationFactory getInstance()
    {
        return instance;
    }

    /**
      *   this method will get the instance of the TestObject
      */
    public TestObject getTestObject()
    {
        /*
         NOTE: this is not a true object factory, since we only create
		 one type of object, but it is a good illustration of
		 how you can control access to a serializable object.
         */
        File f = new File("com.cathail.serialization.tests.TestObject.ser");

        if(f.exists())
        {
            // create the requested object from the serialized file
            try
            {
               object = (TestObject) DeSerializer.deserialize(new
			    FileInputStream(f));
            }
            catch(java.io.FileNotFoundException e)
            {
               object = null;
            }
        }
        else
        {
            /*   the object was never created before, so
                 create the requested object and then serialize
            */

            object = new TestObject();
            object.serialize();
        }

        return object;
    }
}
  
 

All Rights Reserved
Copyright ©  2004 SYS-CON Media, Inc.
  E-mail: [email protected]

Java and Java-based marks are trademarks or registered trademarks of Sun Microsystems, Inc. in the United States and other countries. SYS-CON Publications, Inc. is independent of Sun Microsystems, Inc.