Question

I'm trying to read multiple values using ini4j, the docs say it should be possible with the Options class.

Here is my sample .ini file (./dwarfs.ini)

[dopey]
age = 23
fortuneNumber = 11
fortuneNumber = 33
fortuneNumber = 55

here is the code to read it:

Ini ini = new Ini();
Config conf = new Config();
conf.setMultiOption(true);
ini.setConfig(conf);
ini.load(new FileReader("./dwarfs.ini"));

but fortuneNumber property is just 55 after reading and I'd want it to be an array or a list, anything.

Was it helpful?

Solution

The web presence for the ini4j project contains (among others) very simple tutorials. One of these tutorials explains, how to retrieve multiple values. How could you expect to get a list or an array, when using a fetch method that returns a single reference? Look at the API!

In the tutorial, there is a part explaining multi values:

[ini4j] library introduces MultiMap interface, which is extends normal Map, but allows multiply values per keys. You can simply index values for a given key, similar to indexed properties in JavaBeans api.

There is also an example:

String n1 = sneezy.get("fortuneNumber", 0);  // = 11
String n2 = sneezy.get("fortuneNumber", 1);  // = 22
String n3 = sneezy.get("fortuneNumber", 2);  // = 33
String n4 = sneezy.get("fortuneNumber", 3);  // = 44

In this example, sneezy is a Section, but it should also work with an Ini.

And just to make it complete: An Ini also knows a method List<V> getAll(Object key).

OTHER TIPS

to handle mutliple properties in section use following code :

Ini oINI = new Wini();
Config conf = new Config();
conf.setMultiOption(true);
oINI.setConfig(conf);
oINI.load(new File("....../myfile.ini"));

Do not directly open the INI file in the class creation, set options before, otherwise the options won't be used and by default MultiOption si set to "false".

Have searched a while for this solution.

  1. you need setConfig first, and then load file.
  2. you need use List to handle multiple same values.

here the example:

Ini ini = new Wini();

Config config = new Config();
config.setMultiOption(true);
config.setMultiSection(true);

ini.setConfig(config);   //set config

ini.load(new File(filename));      // load AFTER setConfig

for (String sectionName : ini.keySet()) {
    List<Section> sectionList = ini.getAll(sectionName);  // use List
    for (Section section : sectionList) {
        for (String optionName : section.keySet()) {
            List<String> optionList = section.getAll(optionName);
            for (String optionVaule : optionList) {
                System.out.printf("%s %s %s\n", sectionName, optionName, optionVaule);
            }
        }
    }
}

here the out put:

dopey age 23
dopey fortuneNumber 11
dopey fortuneNumber 33
dopey fortuneNumber 55
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top