views:

1859

answers:

5

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?

+9  A: 

Try:

foo=1,2

String[] foos = properties.getProperty("foo").split(",").
Nick Holt
Simple and elegant, thank you!
ClueMinus
The above line will throw a NullPointerException if property foo isn't found. So make sure to check the property exists or catch/throw the exception if the property is required. If the property is optional then properties.getProperty("foo", "").split(",") could be a safer alternative.
Lee Theobald
+1  A: 

You could use a Map<String,Set<String>>:

Map<String,Set<String>> prop= new HashMap<String,Set<String>>();
Set<String> set = prop.get("foo");
if(set=null) set= new HashSet<String>();
set.add("1");
set.add("2");
prop.put("foo",set);
Pierre
+3  A: 

The java.util.Properties function is pretty limited. If you want support list, you might want try PropertyConfiguration from Apache Commons Configuration,

http://commons.apache.org/configuration/userguide/howto%5Fproperties.html#Using%5FPropertiesConfiguration

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
ZZ Coder
+1  A: 

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.
KLE
+1  A: 

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

Pablojim