Skip to content

Parsers and Writers

Guillaume R edited this page May 2, 2018 · 3 revisions

A FileConfig is linked to one and only one configuration file. If you want more freedom, you can use ConfigParsers and ConfigWriters to parse/write any configuration from/to any file.

ConfigParser

Parsing to a new configuration

Get a ConfigParser from a ConfigFormat and use the parse(input) method to create a new configuration with the read data. You can provide a String, a Reader, an InputStream, a File or an URL.

ConfigFormat<?,?,?> jsonFormat = JsonFormat.fancyInstance();
ConfigParser<?,?> jsonParser = jsonFormat.createParser();
Config c = jsonParser.parse("{\"key\":\"value\", \"key2\":123}");

Parsing to an existing configuration

Use the overloaded method parse(input, destination, parsingMode) to put the parsed data into an existing configuration.

The parsingMode parameter defines how the existing Config will be modified.

  • ParsingMode.REPLACE erases the config and replaces all its content
  • ParsingMode.MERGE puts all the parsed values into the config, but keeps the existing values that aren't present in the newly read data
  • ParsingMode.ADD adds the values that aren't already in the config, and doesn't overwrite any existing data
ConfigFormat<?,?,?> jsonFormat = JsonFormat.fancyInstance();
ConfigParser<?,?> jsonParser = jsonFormat.createParser();
Config c = Config.inMemory();
jsonParser.parse("{\"key\":\"value\", \"key2\":123}", c, ParsingMode.REPLACE);

ConfigWriter

Get a ConfigParser from a ConfigFormat and use the write(config, output) method to create a new configuration with the read data. The output can be a Writer, an OutputStream, a File or an URL.

To produce a String, use writeToString(config).

ConfigFormat<?,?,?> jsonFormat = JsonFormat.fancyInstance();
ConfigWriter<?> jsonWriter = jsonFormat.createWriter();
Config c = Config.inMemory();
c.set("key", "value");
c.set("key2", 123);
String json = jsonWriter.writeToString(c);
System.out.println("JSON config: " + json);

Note: the default charset is UTF_8

Writing mode

When writing to a File, you can choose the writingMode between REPLACE, which overwrites the file, and APPEND, which appends the data to the end of the file.