Properties in java - can we have comma-separated keys with single value?
I want to h开发者_如何学Cave multiple keys (>1) for a single value in a properties file in my java application. One simple way of doing the define each key in separate line in property file and the same value to all these keys. This approach increases the maintainability of property file. The other way (which I think could be smart way) is define comma separated keys with the value in single line. e.g.
key1,key2,key3=value
Java.util.properties doesn't support this out of box. Does anybody did simillar thing before? I did google but didn't find anything.
--manish
I'm not aware of an existing solution, but it should be quite straightforward to implement:
String key = "key1,key2,key3", val = "value";
Map<String, String> map = new HashMap<String, String>();
for(String k : key.split(",")) map.put(k, val);
System.out.println(map);
One of the nice things about properties files is that they are simple. No complex syntax to learn, and they are easy on the eye.
Want to know what the value of the property foo
is? Quickly scan the left column until you see "foo".
Personally, I would find it confusing if I saw a properties file like that.
If that's what you really want, it should be simple to implement. A quick first stab might look like this:
- Open file
- For each line:
trim()
whitespace- If the line is empty or starts with a #, move on
- Split on "
=
" (with limit set to 2), leaving you with key and value - Split key on "
,
" - For each key,
trim()
it and add it to the map, along with thetrim()
'd value
That's it.
Since java.util.Properties
extends java.util.Hashtable
, you could use Properties
to load the data, then post-process the data.
The advantage to using java.util.Properties
to load the data instead of rolling your own is that the syntax for properties is actually fairly robust, already supporting many of the useful features you might end up having to re-implement (such as splitting values across multiple lines, escapes, etc.).
精彩评论