Java Reference
In-Depth Information
Solution
In this example, the
XMLEncoder
object is used to encode the
Settings
object,
which contains program settings information and writes it to the
settings.xml
file.
The
XMLDecoder
takes the
settings.xml
file and reads it as a stream, decoding
the
Settings
object. A
FileSystem
is used to gain access to the machine's file
system;
FileOutputStream
is used to write a file to the system; and
FileIn-
putStream
is used to obtain input bytes from a file within the file system. In this ex-
ample, these three file objects are used to create new XML files, as well as read them
for processing.
//Encoding
FileSystem fileSystem = FileSystems.getDefault();
try (FileOutputStream fos = new
FileOutputStream("settings.xml"); XMLEncoder encoder =
new XMLEncoder(fos)) {
encoder.setExceptionListener((Exception e) -> {
System.out.println("Exception! :"+e.toString());
});
encoder.writeObject(settings);
}
// Decoding
try (FileInputStream fis = new
FileInputStream("settings.xml"); XMLDecoder decoder =
new XMLDecoder(fis)) {
ProgramSettings decodedSettings = (ProgramSettings)
decoder.readObject();
System.out.println("Is same?
"+settings.equals(decodedSettings));
}
Path file= fileSystem.getPath("settings.xml");
List<String> xmlLines = Files.readAllLines(file,
Charset.defaultCharset());
xmlLines.stream().forEach((line) -> {
System.out.println(line);
});