XML Object Cereal
You think that Java’s serialization mechanism has problems? You want to store/serialize an object as XML? Well you can use Java’s XMLEncoder and XMLDecoder classes to serialize an object to XML and then read it back. Want to see some code? Well here it is:
// Encode/Serialize bean to XML MyBean bean = new MyBean(); bean.setName("Bill Gates"); bean.setTitle("Chairman of the Board"); XMLEncoder encoder = new XMLEncoder( new FileOutputStream(filePathStr) ); encoder.writeObject(bean); encoder.close();
In the above code block you instantiated a JavaBean and set the name and title properties. To save the object instance you write out the object using the writeObject method of the XMLEncoder class. How simple is that?
To read in an object from an XML file, you use the XMLDecoder. Here is some sample code:
// Read in an object from an XML file XMLDecoder decoder = new XMLDecoder( new FileInputStream(filePathStr) ); MyBean bean = (MyBean)decoder.readObject(); decoder.close();