With the following properties file:
foo=hello, world!
bar=first,second
I would like to retrieve the first item as a string and the second as an array. I would have thought that getString
vs getStringArray
would deal with this, but it doesn't - getString("foo")
just gets everything before the comma, i.e. "hello".
If I disable delimiter parsing using setDelimiterParsingDisabled
, foo is fine, but this also changes the behaviour of getStringArray("bar")
to return a single-element array!
I can't find how I can explicitly tell it how I want it to interpret an individual config item, either as a string or as an array. I don't want to put the config items into separate config files with different delimiter rules, and I'd prefer to use a comma as the delimiter for the getStringArray case.
To elaborate, this snippet prints either hello - 2
or hello, world! - 1
- I want it to print hello, world! - 2
!
AbstractFileConfiguration config = new PropertiesConfiguration();
config.setFileName("C:\\temp\\temp.properties");
//config.setDelimiterParsingDisabled(true);
config.load();
System.out.println(config.getString("foo") + " - " + config.getStringArray("bar").length);
As you found out, Commons Config lacks something like a getPlainString()
method. Here are some suggestions for workarounds.
I think using a different list delimiter is the easiest to implement. If you need something more complex, consider the other two:
Works as long as you don't need to interpret the same value as a String and as an array.
properties file:
foo=hello, world!
bar=first;second
Code:
AbstractFileConfiguration config = new PropertiesConfiguration();
config.setFileName("C:\\temp\\temp.properties");
config.setListDelimiter(';');
config.load();
System.out.println(config.getString("foo") + " - " + config.getStringArray("bar").length);
Easily done with String.split(). A simple static method will do:
public static String[] gerStringArray(Configuration config, String key)
Or create a subclass of PropertiesConfiguration
and override the getStringArray()
and getList()
methods.
One for settings data where you know what format the data will have. Here you can activate delimiter parsing.
And one for text data where you might have arbitrary data. Here you should deactivate delimiter parsing.
This has the additional advantage of separating settings and text data.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With