Introduction: How to Save/load Java Classes to a Stream (or File) in XML Format
There are a lot of simple ways to save or to load a java class to a stream or file in XML format. For example:
- you can use java.beans.XMLEncoder and java.beans.XMLDecoder if your class is a JavaBean
- you can use storeToXML and loadFromXML methods of the java.util.Properties class (if your class extends from a Properties)
BUT what about a simple way to save or load a java class in a XML format that you can simply define?
Well, there is a simple way based on JAXB.
Step 1: The Short Way
1. download Ardulink from here http://www.ardulink.org
2. insert in your java project ardulink.jar
3. create your java class with JAXB annotation (see Example.zip in the next step)
4. use JAXBReaderWriter class in ardulink.jar to store or retrieve your java class in XML format
For instance if your class is named Configuration you have just to write
JAXBReaderWriter readerWriter = new JAXBReaderWriter(Configuration.class);
// You can read from a file
Configuration configuration = readerWriter.read(file);
// And save to a stream
Note: Ardulink is an open source project to control and coordinate Arduino boards from Java. So you don't need all classes from Ardulink to save and load classes to and from XML format. JAXBReaderWriter is just an utility class used in Ardulink features. You can extract it from ardulink.jar and reuse. Please read the license before.
Step 2: The Complete Way
Just as the short way but you can read JAXBReaderWriter code and modify it as you want since it is a class from the open source project Ardulink.
In the Example.zip you can find some classes that can be stored and retrieved with JAXBReaderWriter class. These classes are used to made the intro image of this mini tutorial.
Note: JAXBReaderWriter manages correctly the character set. It uses explicity UTF-8 and not the platform default. So you can use file created to and from several systems and if you use non ASCII characters you can manage strings correctly.
We have a be nice policy.
Please be positive and constructive.