Write your own file format

Implement SettingsFileFormat so a structured settings file such as TOML, JSON or INI is synced key by key, and follow its round-trip contract.

Last updated

Steps

When your settings file is not plain key=value or key:value lines, write a SettingsFileFormat for it. This guide shows the interface, the rules it must follow and a working implementation.

Prerequisites#

The interface#

public interface SettingsFileFormat {
    Map<String, String> read(Reader reader) throws IOException;
    void write(Map<String, String> values, Writer writer) throws IOException;
}

Keys and values are plain strings. Flatten nested values into dotted keys: the fov setting in a video section becomes video.fov, and write nests it again.

Steps#

1. Implement read#

@Override
public Map<String, String> read(Reader reader) throws IOException {
    Map<String, String> values = new LinkedHashMap<String, String>();
    BufferedReader lines = new BufferedReader(reader);
    String section = "";
    String line;
    while ((line = lines.readLine()) != null) {
        line = line.trim();
        if (line.isEmpty() || line.startsWith("#")) {
            continue;                                   // blank lines and comments
        }
        if (line.startsWith("[") && line.endsWith("]")) {
            section = line.substring(1, line.length() - 1).trim();
            continue;
        }
        int eq = line.indexOf('=');
        if (eq <= 0) {
            continue;                                   // not a setting: skip it, don't throw
        }
        String key = line.substring(0, eq).trim();
        String value = line.substring(eq + 1).trim();
        values.put(section.isEmpty() ? key : section + "." + key, value);
    }
    return values;
}

Rules for read:

2. Implement write#

@Override
public void write(Map<String, String> values, Writer writer) throws IOException {
    // Group the keys by section, keeping the order in which sections and keys first appear.
    Map<String, Map<String, String>> sections = new LinkedHashMap<String, Map<String, String>>();
    for (Map.Entry<String, String> e : values.entrySet()) {
        int dot = e.getKey().indexOf('.');
        String section = dot < 0 ? "" : e.getKey().substring(0, dot);
        String key = dot < 0 ? e.getKey() : e.getKey().substring(dot + 1);
        Map<String, String> keys = sections.get(section);
        if (keys == null) {
            keys = new LinkedHashMap<String, String>();
            sections.put(section, keys);
        }
        keys.put(key, e.getValue());
    }
    // Keys without a section go first, so they aren't read back as part of one.
    Map<String, String> top = sections.remove("");
    if (top != null) {
        writeKeys(top, writer);
    }
    for (Map.Entry<String, Map<String, String>> s : sections.entrySet()) {
        writer.write("[" + s.getKey() + "]\n");
        writeKeys(s.getValue(), writer);
    }
}

Rules for write:

3. Register it#

Make one shared instance and pass it to file or directory:

ModSettings.builder("mymod", "My Mod", "2.1.0")
        .file("config/mymod.cfg", SectionedFormat.INSTANCE)
        .build();

The full class is in A sectioned config file.

The contract#

Rule What it means What breaks otherwise
Round trip Reading what write wrote gives the same map, in the same order. Settings Saver sees changes the player never made, and saves them.
Tolerant reading read sees whatever is on disk: hand-edited files, files from older or newer versions of your mod, half-migrated files. Skip what you can't parse. An exception means that file is not synced at all in that round.
Stateless One instance is shared by every file it is registered for and is called from several threads. Keep no state between calls. Files mix up each other's values.
Text only Files are UTF-8 text. Binary content is corrupted.

Throwing IOException is allowed. From read, the file is skipped and the error logged, until the file can be read. From write, the old file is kept unchanged: Settings Saver writes into a temporary file that replaces the real one only when writing finished, so the game never sees a partly written file.

Settings Saver uses your format for both the file in the game directory and the profile's copy of it.

Using a parsing library#

The API has no dependencies, and your format runs early in the launch (see When plugins run). A format that uses a library, such as a JSON or TOML parser, needs that library to be loadable at that point on every loader you ship for. A format written with the JDK alone, like the one above, has no such requirement.

How a value is spelled (quoting, number format) is up to your format, as long as it reads back the same.

Checklist#

Next steps#