views:

2360

answers:

3

Hi.

I'm trying to find the best way to save the state of a simple application. From a DB point-of-view there are 4/5 tables with date fields and relationships off course.

Because the app is simple, and I want the user to have the option of moving the data around (usb pen, dropbox, etc), I wanted to put all data in a single file.

What is the best way/lib to do this?

XML usually is the best format for this (readability & openness), but I haven't found any great lib for this without doing SAX/DOM.

+4  A: 

If you want to use XML, take a look at XStream for simple serialization of Java objects into XML. Here is "Two minute tutorial".

If you want something simple, standard Java Properties format can be also a way to store/load some small data.

Peter Štibraný
java.util.Properties also does XML.
Michael Myers
XStream seems just what I was looking for. Do you know about any code available to optimize writings in this lib? I shouldn't be writing to disk on every change.
mrlinx
It's totally up to you to initiate writing. XStream won't do any automatic saving for you.
Peter Štibraný
A: 

2 other options you might consider -

  • Hsqldb is a small sql db written in java. More relevant for your purposes, it can be configured to simply write to a csv file as it's data store, so you could conceivably use it's text output as a portable datastore and still use sql, if that's what you prefer.
  • A second option might be to write the datastore directly to a serialized file either directly or through a library like prevayler. Very good performance and simple to implement, cons are the fragility and opacity of the format.

But if the data is small enough, xml is probably much less bother.

Steve B.
+1  A: 

consider using plain JAXB annotations that come with the JDK:

@XmlRootElement  
private class Foo {  
    @XmlAttribute  
    private String text = "bar";
}

here's a blog-post of mine that gives more details on this simple usage of JAXB (it also mentiones a more "classy" JAXB-based approach -- in case you need better control over your XML schema, e.g. to guarantee backwards compatibility)

netzwerg