Storing data: initial ideas - BBK-PiJ-2014-66/cw4 GitHub Wiki
Storing data to file: initial ideas
The coursework document specifies :
When the application is closed, all data must be stored in a text file called "contacts.txt". This file must be read at startup to recover all data introduced in a former session (the format of the file if up to you: you can use XML, comma-separated values (CSV), or any other format).
Possibility one Java Serialization
On the Moodle Keith suggested that we look at the use of Java Serialization particularly the Lars Vogel Tutorial. This is attractively simple but has the disadvantage that that approach does not produce a text output as so does not strictly meet the spec (a binary file called contacts.txt would seem to be a really bad idea). To get around the problem one could encode the binary for instance using base64 encoding. Getting ugly and in any case making the file human readable would seem to be a good idea. So reject for now but keep as a backup plan in case the use of 3rd party libraries is verboten.
Possibility two DIY file write
Write code explicitly dump to a custom text format. Done too much of this in the past. This is a bit of a nightmare requiring how to encode user fields that include the delimiters.
Possibility three XML or JSON with DIY writer
Use a decent human and other readable exchange format. XML is a good idea. JSON is another good (better like betamax). But once again I have wasted a lot of time maintaining/extending DIY raw XML writer in the past. Want to find better approach.
Possibility four use XSTREAM to read/write XML
There are many many ways of writing XML in java. Looking through these the easiest for a newbie is XSTREAM that XStream is a simple library to serialize objects to XML and back again. It uses reflection. But it introduces a 3rd party Jar into the project So it is probably forbidden May carry on and then strip back to Possibility one Java Serialisation
Possibility five use Java SE methods to read/write XML
Useful StackOverFlow contribution. Of the four possibilities XMLStreamWriter looks simplest to you (but one would end up with DIY writer that used XML mark-up).
Approach taken
After pondering the above decided to try two approaches:
- Use Serialization with some kind of encoding to text
- Use XSTREAM and write XML
Final thoughts Followed the above approaches and implemented both. In the end the development branch version uses XSTREAM whereas the to-be-marked-lite version uses Java Serialization with base64 encoding.