Serialization

Serialization Print E-mail
Contributed by Joe   
Monday, 17 July 2006

What is serialization.?

The process of storing and retrieving objects in an external file is called serialization.

Writing an object to a file is referred to as serializing the object, and reading an object from a file is called deserializing an object. Serialization is concerned with writing objects and the fields they contain to a stream.

Two classes from the java.io package are used for serialization. An ObjectOutputStream object manages the writing of objects to a file, and reading the objects back is handled by an object of the class ObjectInputStream.

Writing an Object to a File

You just need to create an ObjectOutputStream object with the following statements, Note: ObjectOutputStream must be constructed on another stream.

File theFile = new File("newFile");
// Create the object output stream for the file
ObjectOutputStream objectOut = null;
try {
  objectOut = new ObjectOutputStream(new FileOutputStream(theFile));
} catch(IOException e) {
  System.exit(e.toString());
}

Above code does not result in a stream that is particularly efficient since each output operation will write directly to the file. In fact you can want to buffer write operations on the file in memory, like following code

  objectOut = new ObjectOutputStream(
                new BufferedOutputStream(
                  new FileOutputStream(theFile)));

Call the writeObject() method to write an object to a file

try {
  objectOut.writeObject(myObject);
} catch(IOException e) {
  e.printStackTrace(System.err);
  System.exit(1);
}

You can write data of any of the primitive types using the methods defined in the ObjectOutputStream class for this purpose.

writeByte(int b)
writeByte(byte b)
writeChar(int ch)
writeShort(int n)
writeInt(int n)
writeLong(long n) 
writeFloat(float f)
writeDouble(double d)

Transient Data Members of a Class

If your class has fields that are not serializable,you can declare them as transient. For example:

public class MyClass implements Serializable {
  transient protected Graphics g;  
}

Reading an Object from a File(Deserializing Objects)

First, to create an ObjectInputStream object for the file.

File theFile = new File("newFile");
ObjectInputStream objectIn = null;
try {
  objectIn = new ObjectInputStream(new FileInputStream(theFile));
} catch(IOException e) {
  e.printStackTrace(System.err);
  System.exit(1);
}

Second,to call readObject() method to read an object from the file:

Object myObject = null;
try {
  myObject = objectIn.readObject();
} catch(ClassNotFoundException e){
  e.printStackTrace(System.err);
  System.exit(1);
} catch(IOException e){
  e.printStackTrace(System.err);
  System.exit(1);
}

Last Updated ( Monday, 17 July 2006 )

  home              contact us

 

©2006-2010 DeveloperZone.biz   All rights reserved     powered by Mambo Designed by Siteground