Reputation: 393
It seems that java.util.Properties assumes one value per propery key. That is,
foo=1
foo=2
is not expected,
Is there a class for this kind of multi-value property sheet, which also provides the load method?
Upvotes: 39
Views: 95957
Reputation: 34311
Try:
foo=1,2
String[] foos = properties.getProperty("foo", "").split(",");
Upvotes: 72
Reputation: 851
If you have a more complex example you might use the following:
# pairs of properties
source1=foo
target1=bar
source2=anotherFoo
target2=regardingBar
source3= ...
In your code you will have to search:
Map<String, String> myMap = new HashMap<>();
for (int i=1; i<max; i++) {
String source = properties.get("source" + i);
String target = properties.get("target" + i);
if (source == null || target == null) {
break;
}
myMap.put(source, target);
}
Drawback: updating the properties file. If you remove values *2, all the following values will not be added. To improve you might want to replace the break with a continue and stick to a maximum of allowed pairs.
Upvotes: 1
Reputation: 8582
This won't provide the load method but a place to store them you could use a apache commons multivaluemap:
"A MultiValueMap decorates another map, allowing it to have more than one value for a key. "
This is often a requirement for http request parameters...
http://commons.apache.org/collections/apidocs/org/apache/commons/collections/map/MultiValueMap.html
Upvotes: 0
Reputation: 24159
Correct answer by Nick.
Or, if you can give a different subname to each value, you could have your properties be:
my.properties
foo.title=Foo
foo.description=This a big fat foo.
Upvotes: 4
Reputation: 75456
The java.util.Properties function is pretty limited. If you want support list, you might want try PropertyConfiguration from Apache Commons Configuration,
With it, you can set any delimiters to your list and it will split for you automatically. You can also do other fancy things in properties file. For example,
foo=item1, item2
bar=${foo}, item3
number=123
You can retrieve it like this,
Configuration config = new PropertiesConfiguration("your.properties");
String[] items = config.getStringArray("bar"); // return {"item1", "item2", "item3"}
int number = config.getInt("number", 456); // 456 is default value
Upvotes: 23