For an application that I'm writing, I wanted to be able to persist a large number of objects.  I wanted to avoid the complexities of a real database and the opaqueness and fragility of Java object serialization.  What I really wanted was the ability to turn any object into a a bit of XML that I could save and load at will, without having to do a lot of work defining the mapping between the Java object and the XML.  

There are a number of  standard Java APIs to go back and forth between Java and XML, but they all seem a bit complex for what I wanted to do.   Luckily, I stumbled upon XStream.  XStream is a simple API for doing exactly what I wanted:  serialize objects to XML and back again.  The API is quite simple to use.  To serialize an object to a file I use the code:

            XStream xstream = new XStream();
BufferedWriter writer = new BufferedWriter(new FileWriter(file));
xstream.toXML(myObject, writer);

And to load the object I use:

                BufferedReader reader = new BufferedReader(new FileReader(file));
myObject = (MyObject) xstream.fromXML(reader);

It couldn't be any easier than that. 

XStream is fast, simple, and easy to use.  Highly recommended.



Post a Comment:
Comments are closed for this entry.

This blog copyright 2010 by plamere