Serializing Java Objects as XML
Until the release of Java 2 Standard Edition (J2SE) Version 1.4, Java objects could only be serialized to a proprietary, binary format. Now, Java objects can be serialized as XML documents, a feature of the new long-term persistence API for JavaBeans. This article illustrates how to use this new feature.
To try the example programs that accompany this article, you will need the following tools:
- Java 2 Standard Edition (J2SE) SDK 1.4
- Your favorite text editor
XML ArchivesJava objects that are serialized using the long-term persistence classes are stored as Java XML archives. Bean.xml is an example of a simple, archived JavaBean. JFrame.xml is an example of an archived GUI component. (See "Resources" for links to more information on the Java XML archive format.)
Java XML archives are created with java.beans.XMLEncoder. They are read with java.beans.XMLDecoder.
Writing Serialized Objects
To write (serialize) a Java object to a file with the serialized object binary format, you use the following algorithm:
// Create output streams. FileOutputStream fos = new FileOutputStream("foo.dat"); ObjectOutputStream oos = new ObjectOutputStream(fos); // Write object. oos.writeObject(aFoo);
Writing Archived Objects
Writing (archiving) a Java object to an XML archive is just as easy as writing it to a serialized object binary file. However, instead of using java.io.ObjectOutputStream, you use java.beans.XMLEncoder. Here is the algorithm:
// Create output stream. FileOutputStream fos = new FileOutputStream("foo.xml"); // Create XML encoder. XMLEncoder xenc = new XMLEncoder(fos); // Write object. xenc.writeObject(aFoo);
Reading Serialized Objects
To read (deserialize) a Java object from a serialized object binary file, you use the following algorithm:
// Create input streams. FileInputStream fis = new FileInputStream("foo.bin"); ObjectInputStream ois = new ObjectInputStream(fis); // Read object. Foo aFoo = (Foo) ois.readObject();