Friday, November 7, 2008

Serializing and Deserializing Objects

The serialization mechanism in Java provides the means for persisting objects beyond a single run of a Java program. To serialize an object, make sure that the declaring class implements the java.io.Serializable interface. Then obtain an ObjectOutputStream to write the object to and call the writeObject() method on the ObjectOutputStream. To deserialize an object, obtain an ObjectInputStream to read the object from and call the readObject() method on the ObjectInputStream. The following code excerpts illustrate how an object of type MyClass is serialized and deserialized.


1. // Serialize an object of type MyClass
2. MyClass myObject = new MyClass();
3. FileOutputStream fos = new FileOutputStream("myObject.ser");
4. ObjectOutputStream oos = new ObjectOutputStream(fos);
5. oos.writeObject(myObject);
6. oos.flush();
7. oos.close();
8.
9. // Deserialize the object persisted in "myObject.ser"
10. FileInputStream fis = new FileInputStream("myObject.ser");
11. ObjectInputStream ois = new ObjectInputStream(fis);
12. MyClass myDeserializedObject = (MyClass)ois.readObject();
13. ois.close();

Lines 1-5 serialize the object myObject of type MyClass. On Line 3, the file output stream fos is created for the file named myObject.ser. The object is actually persisted in this file on Lines 5-7. Lines 9-13 read the object back from the file myObject.ser. If you list the files in the directory where this code's .class file is stored, you will see a new file called myObject.ser added to the listing. The Lines 1-7 and 9-13 can be in two completely different processes run at different times.

No comments: