I wanted a way to create a JSON configuration file in JavaFX in a cross-platform manner, and that would map easily to a properties object. I also wanted it to update the configuration file should any property change during the life of the application.
I used Gson to do the object-to-JSON mappings.
I created two classes to do this. In this example the properties class has 5 string properties, hence why the default instantiation has 5 empty strings:
/** * The Configuration singleton class creates a default config file in a user's home directory * if it does not exist and provides access to configuration data through out the application. * It also provides a method to modify configuration details and persist to file. */ publicclassConfiguration{ privatestaticfinal Logger log = LogManager.getLogger();
private Properties properties; public Properties getProperties(){ return properties; }
/** * Helper method to construct the Config path in an OS-agnostic way * * @return Full path of config file */ privatestatic String getConfigPath(){ return Utils.combinePath(System.getProperty("user.home"), Arrays.asList(".myApp", "config.json")); } }
The getConfigPath() function ensures that the configuration is read and written to the user’s home directory, in a subdirectory called .myApp. You can of course define somewhere else, but bear in mind with this setup the user running the application is who’s home the file will be written into.
These classes weren’t only the work of me either - the onPropertyUpdated & updateProperties capabilities are the work of Ben Burrough.