Configuration files

Configuration files #

It is common practice for an application to store parameters (e.g. user-specific settings) in configuration files.

A configuration file may be edited manually and/or via a graphical interface.

Configuration files may use different serialization formats. Some popular formats are INI, JSON, TOML, YAML or XML.

in Java #

Java provides native support for at least two configuration file serialization formats: XML and the so-called “property file” format.

We introduce here the latter.

A property file usually:

  • has extension .properties,
  • may have commented line (starting with # or !),
  • contains one key=value pair per (non-commented) line.

Example. In our game, the file config.properties has two key=value pairs:

animationDuration=1
resolution=1920x1080

More details about the syntax of property files (escaped characters, spaces, etc.) can be found here.

Reading a property file #

The content of a property file can be loaded in memory and modified as an associative array, instance of the class Properties (which implements the interface Map).

For instance, the content of a property file can be loaded as follows:

Properties properties = new Properties();
try {
    properties.load(new FileInputStream("path/to/config.properties"));
} catch (IOException e) {
    throw new RuntimeException(e);
}

Then a value can be read with the method getProperty (among other possibilities), as follows:

String resolution = properties.getProperty("resolution");
float duration = Float.parseFloat(properties.getProperty("animationDuration"));

Writing to a property file #

The content of a property file can be modified with the methods setProperty and store (among other possibilities), as follows:

String path = "path/to/config.properties";
Properties properties = new Properties();
try {
    // load the file as an associative array
    properties.load(new FileInputStream(path));
    // modify the associative array
    properties.setProperty("animationDuration", Float.toString(0.5f));
    // replace the content of the property file with the
    // content of the associative array
    properties.store(new FileOutputStream(path));
} catch (IOException e) {
    throw new RuntimeException(e);
}