In my tiny little standalone Java application I want to store information.
My requirements:
- read and write java objects (I do not want to use SQL, and also querying is not required)
- easy to use
- easy to setup
- minimal external dependencies
I therefore want to use jaxb to store all the information in a simple XML-file in the filesystem. My example application looks like this (copy all the code into a file called Application.java
and compile, no additional requirements!):
@XmlRootElement
class DataStorage {
String emailAddress;
List<String> familyMembers;
// List<Address> addresses;
}
public class Application {
private static JAXBContext jc;
private static File storageLocation = new File("data.xml");
public static void main(String[] args) throws Exception {
jc = JAXBContext.newInstance(DataStorage.class);
DataStorage dataStorage = load();
// the main application will be executed here
// data manipulation like this:
dataStorage.emailAddress = "[email protected]";
dataStorage.familyMembers.add("Mike");
save(dataStorage);
}
protected static DataStorage load() throws JAXBException {
if (storageLocation.exists()) {
StreamSource source = new StreamSource(storageLocation);
return (DataStorage) jc.createUnmarshaller().unmarshal(source);
}
return new DataStorage();
}
protected static void save(DataStorage dataStorage) throws JAXBException {
jc.createMarshaller().marshal(dataStorage, storageLocation);
}
}
How can I overcome these downsides?
- Starting the application multiple times could lead to inconsistencies: Several users could run the application on a network drive and experience concurrency issues
- Aborting the write process might lead to corrupted data or loosing all data
ServerSocket
with a fixed port. If you start another instance it will throw an exception and in the catch clause you can just quit the second instance. However this approach might fail if another app uses the same port. – Ptolemy