It looks like you might want to save the database. However, to avoid the complexity of the database, one simple solution for storing POJOs in the file system is to serialize them in an XML document. The Java 1.6 API includes the JAXB framework found in the javax.xml.bind package. To use JAXB, you essentially annotate your POJO and create marshals and non-marshal methods, for example:
@XmlRootElement(name="Foo") public class Foo { @XmlElement(name="Bar") public int mBar; public static void marshal(Foo foo, OutputStream out) IOException { try { JAXBContext jc = JAXBContext.newInstance(Foo.class); Marshaller marshaller = jc.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); marshaller.marshal(qaConfig, out); } catch (JAXBException ex) { throw new IOException(ex); } finally { out.close(); } } public static Foo unmarshal(InputStream in) throws IOException { try { JAXBContext jc = JAXBContext.newInstance(Foo.class); Unmarshaller unmarshaller = jc.createUnmarshaller(); return (Foo)unmarshaller.unmarshal(in); } catch (JAXBException ex) { throw new IOException(ex); } finally { in.close(); } } }
Suppose you save an instance of Foo where mBar is 42, then this solution will create an XML file, for example:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?> <Foo> <Bar>42</Bar> </Foo>
jenglert
source share