November 25, 2017
Hot Topics:

Serializing Java Objects as XML

  • June 27, 2002
  • By Thornton Rose
  • Send Email »
  • More Articles »

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 Archives

Java 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.

WriteQuark demonstrates the above algorithm. It is a simple program that serializes an instance of Quark to a file.

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.

WriteQuarkXML demostrates the above algorithm. It is a simple program that archives an instance of Quark to an XML archive.

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();

ReadObj demonstrates the above algorithm. It is a simple program that deserializes an object from a binary file created by WriteQuark.

Page 1 of 2

Comment and Contribute


(Maximum characters: 1200). You have characters left.



Enterprise Development Update

Don't miss an article. Subscribe to our newsletter below.

Sitemap | Contact Us

Thanks for your registration, follow us on our social networks to keep up-to-date