-
Notifications
You must be signed in to change notification settings - Fork 28
Parsers and Writers
A FileConfig is linked to one and only one configuration file. If you want more freedom, you can use ConfigParser
s and ConfigWriter
s to parse/write any configuration from/to any file.
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}");
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);
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
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.