To read the file at the start of the program, you can just put the reading code at the start.
But to make sure it is saved when you exit your program from anywhere, you could use a shutdown hook:
Runtime.getRuntime().addShutdownHook(new Thread(() -> {
// Shutdown code here
}));
Which you register at the start of the program. It gets called when the JVM shuts down. By the doc:
The Java virtual machine shuts down in response to two kinds of events:
- The program exits normally, when the last non-daemon thread exits or when the exit (equivalently, System.exit) method is invoked, or
- The virtual machine is terminated in response to a user interrupt, such as typing ^C, or a system-wide event, such as user logoff or system shutdown.
Now at the start of your program you would do something like this:
public static void main(String... args) {
// getConfig() returns a configuration object read from a file
// Or a new object if no file was found.
Configuration config = getConfig();
Runtime.getRuntime().addShutdownHook(new Thread(() -> {
...
// Note that I'm not appending to, but overwriting the file
ObjectOutputStream outputStream =
new ObjectOutputStream(new FileOutputStream("myConfigFile"));
outputStream.writeObject(config); // write the config object.
...
}));
// Rest of the program, using 'config'
}
It is important to note that, because the shutdown hook is executed at the end of the program, it will write the eventual state of the config object. So changes that are made to 'config' during the program, are taken into account.
For objects to be able to be written like this, they need to implement java.io.serializable
and so do all of their fields. Except for fields that have the transient
qualifier.
The config object might look something like this:
public class Configuration implements java.io.Serializable {
// transient -> Will not be written or read.
// So it is always 'null' at the start of the program.
private transient Client lastClient = null;
// 'Client' must also implement java.io.serializable,
// for 'Configuration' to be serializable.
// Otherwise, an exception is thrown when writing the object.
private List<Client> clients = new ArrayList<Client>();
// 'String' already implements java.io.serializable.
private String someString;
...
}