【问题标题】:ini4j store method changes the comment characterini4j store 方法更改注释字符
【发布时间】:2015-10-21 12:00:31
【问题描述】:

我想更改 ini 文件部分中的键条目。我使用 ini4j 库。所以我写了下面的代码。我可以更改条目,但还有其他我不想要的更改:

  • 替换“;”用“#”表示注释行
  • 在 section 和 cmets 之间添加空行

那我该如何解决呢?

这是我的预期:

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

这是编辑后的文件:

[section1]
key1=40
key2=30

[section2]
key1=10
key2=20

#section3

[section3]
key1=10
key2=20

我的代码:

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();
    }
}

有没有办法改变默认的评论字符?

【问题讨论】:

    标签: java file file-io io ini4j


    【解决方案1】:

    显然,即使 ini4j 可以读取带有 ;# 的 cmets,当您必须将它们写入 ini 文件时它也不会保存。

    如果您检查 ini4j 项目的AbstractFormatter 类,您可以看到写入时唯一重要的注释运算符是#,如果您可以访问源代码,您可以使用自定义更改它评论运算符,应该可以工作。

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

    至于空行,它们只是美学。同样,如果您可以访问源代码,您可以自己编辑它(注释 thisthis 行?),但我想如果您在此库生成后重新格式化您的 ini 文件会更容易并删除所有空行。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-03
      相关资源
      最近更新 更多