Configuration properties using the same key to create an array / list

13,728

Solution 1

Your example looks fine to me. If you specify a list of values using the same key, they are treated as a list, and the following should work:

reject.reason = Lorem ipsum sit amet nr. 1
reject.reason = Lorem ipsum sit amet nr. 2
reject.reason = Lorem ipsum sit amet nr. 3
reject.reason = Lorem ipsum sit amet nr. 4

In your Java code:

PropertiesConfiguration config = new PropertiesConfiguration("gui.properties");
String[] reasons = config.getStringArray("reject.reason");

http://commons.apache.org/configuration/userguide/howto_properties.html#Lists_and_arrays

Solution 2

You could store them in a .properties file and name as ...

key.0=line0  
key.1=line1  
key.2=line2

Then in your code iterate through properties with a for loop looking for "key." + i until you get a null back.

I have done this in the past to enumerate and configure com ports and it works well.

Share:
13,728
Mike Minicki
Author by

Mike Minicki

Updated on June 04, 2022

Comments

  • Mike Minicki
    Mike Minicki almost 2 years

    I would like to store the source for html select boxes in a configuration file. These contain a lengthy strings that don't change often (but occassionaly do):

    • Lorem ipsum sit amet nr. 1
    • Lorem ipsum sit amet nr. 2
    • Lorem ipsum sit amet nr. 3
    • Lorem ipsum sit amet nr. 4

    I already use commons-configuration. Is it possible to store them using the same property keys in some kind of configuration object (XMLConfiguration, HierarchicalConfiguration, etc.)? I mean to be able to retrieve them in one go using interface similar to getStringArray() (or list)? Example:

    // reject.reason = Lorem ipsum sit amet nr. 1
    // reject.reason = Lorem ipsum sit amet nr. 2
    // reject.reason = Lorem ipsum sit amet nr. 3
    // reject.reason = Lorem ipsum sit amet nr. 4
    
    config.getStringArray(reject.reason)
    

    I don't want to keep them separated on the same line because, first, the reasons are lengthy, and second, there are lots of reasons (> 10).

    I don't want to store them in enums either, b/c it will be impossible to change them without recompiling the code.

    Any hints on how to achieve this?

  • extraneon
    extraneon over 13 years
    That's what I was writing :) You could even wrap the standard Configuration object in your own wrapper which does this for you.
  • Mike Minicki
    Mike Minicki over 13 years
    Right, that was my first thought as well. I just can't believe there isn't a ready solution for this use case out there. Furthermore, I feel it's already provided by commons-configuration and I just can't find a clear info on how to get it. I'll just try with my gut and will just use the above mentioned now.
  • Mike Minicki
    Mike Minicki over 13 years
    Great, thanks, dogbane! Do you know if commons-configuration has some support for UTF-8 encoded resource bundles by any chance?