4

I want to change the entry of a key in a section of an ini file. I use the ini4j library. So I wrote the code below. I can change the entry but there are also other changes which I don't want:

  • replacement of ";" with "#" which indicates comment lines
  • addition of blank lines between sections and comments

So how can I solve it?

this is what I expected:

[section1]
key1=40
key2=30
[section2]
key1=10
key2=20
;section3
[section3]
key1=10
key2=20

this is the file after editing:

[section1]
key1=40
key2=30

[section2]
key1=10
key2=20

#section3

[section3]
key1=10
key2=20

My code:

public static void setEntry(String filePath, String fileName, String sectionName, String keyName, String entry)
        throws IOException {
    String path = filePath.concat(fileName);
    FileInputStream inputStream = null;
    try {
        inputStream = new FileInputStream(path);
        Ini ini = new Ini(inputStream);
        ini.getConfig().setStrictOperator(true);
        Section section = ini.get(sectionName);
        if (section != null) {
            if (section.containsKey(keyName)) {
                section.put(keyName, entry);
            }
            else {
                section.add(keyName, entry);
            }
        }
        else {
            section = ini.add(sectionName);
            section.add(keyName, entry);
        }

        File iniFile = new File(path);
        ini.store(iniFile);
    }
    catch (IOException e) {
        e.printStackTrace();
    }
    finally {
        inputStream.close();
    }
}

Is there a way to change default comment character?

Ceren Baş
  • 41
  • 3

1 Answers1

0

Apparently, even when the ini4j can read comments with ; and #, it doesn't save this when you have to write them to an ini file.

If you check the AbstractFormatter class of the ini4j project, you can see that the only comment operator that it matters when writes is #, if you have access to the source code, you can change it with your custom comment operator and should work.

abstract class AbstractFormatter implements HandlerBase
{
    private static final char OPERATOR = '=';
    private static final char COMMENT = '#';    // <--- change this to ';'
    ...

As for the empty lines, they are just aesthetics. Again, if you have access to the source code, you can edit it by yourself (commenting this and this lines?), but I guess is easier if you just re-format your ini file after being generated by this library and remove all empty lines.

Alex S. Diaz
  • 2,637
  • 2
  • 23
  • 35