Java XMLEncoderto save the object,XMLDecoderRestore with
Javaobject with theXML formatHere is a sample program that saves in
For XML output, use theXMLEncoderto be used.
andXMLDecoderA sample program to restore a saved object is also presented at the same time using
sample program
- Fields declared private are preserved when Getter and Setter methods are defined.
- Only if there is a change in a variable, it is saved in an XML file.
- HashMap, java.util.ArrayList, etc. can also be specified as objects to be saved. ArrayList, etc. This is useful for storing the state of objects in a simple manner.
// Output byte data to file
fileStream = new FileOutputStream(path);
fileStream.write(xmlbuff);
fileStream.flush();
} finally {
if (enc != null) {
enc.close();
}
if (out != null) {
out.close();
}
if (fileStream != null) {
fileStream.close();
}
}
}
/**
* Restores the object from the XML file at the specified path [path].
* *XML files must be saved using java.beans.XMLEncoder.
* @param path The path where the object is stored.
* @throws FileNotFoundException
* If the file indicated by the specified path name does not exist
*/
public static Object readXML(String path) throws FileNotFoundException {
XMLDecoder d = null;
try {
d = new XMLDecoder(new BufferedInputStream(
new FileInputStream(path)));
return d.readObject();
} finally {
if (d != null) {
d.close();
}
}
}
*The following class is used as a sample of a class to be saved.
Execution Result
◆Example of Execution
// Restore instance of FreeSoft class from XML
FreeSoft freeSoft2 = (FreeSoft)readXML(“C:\\FreeSoft.xml”);
System.out.println(“Soft name:”+freeSoft2.getName());
System.out.println(“URL:”+freeSoft2.getUrl());
} catch (Exception e) {
e.printStackTrace();
}
}
◆Output result
Software name: Chat & Messenger Chat and Messenger! URL: https://chat-messenger.com/
◆C:\FreeSoft.xml contents
Points to keep in mind when using this service
XMLEncoder and java.beans.XMLDecoder classes, but in practical use with Chat&Messenger, we have confirmed that in extremely rare cases, when outputting to XML with java.beans. XMLEncoder.
ParseException is logged to "Standard Error Output" when a 0-byte file is read.
The reason for this is that the file becomes empty when the FileOutputStream instance is created.
I believe it occurs when the Java process is shut down after instantiating the FileOutputStream but before outputting the XML data.
Chat&Messenger has created backup files to work around this problem.