【问题标题】:How to read multiple options into a list or array with ini4j?如何使用 ini4j 将多个选项读入列表或数组?
【发布时间】:2017-10-23 15:45:02
【问题描述】:

我想要一个 INI 文件,其中的一个部分包含一组具有相同选项键的选项值。换句话说,我想在 ini 文件中表示一个数组。我的问题是只有最后一个值被读入数组或列表,这取决于我使用的 getAll 方法:

.ini 文件:

[FTP]
; Access FTP server?
active = false
file.pattern = VA_.*.(csv|dat)$
#file.pattern = VA_.*(\\.(?i)(csv|dat))$
delete.after.download = false

[SFTP]
; Access FTP server?
active = true
file.pattern = VA_.*.(csv|dat)$
#file.pattern = VA_.*(\\.(?i)(csv|dat))$
delete.after.download = false

[SMB]
; Access SMB target?
active = false

[SCP]
; Access SCP target?
active = false

[FTP_Accounts]
ftpAccount = /aaa/xxx
ftpAccount = /bbb/xxx
ftpAccount = /ccc/xxx
ftpAccount = /ddd/xxx
ftpAccount = /eee/xxx
ftpAccount = /fff/xxx

下面的 Java 代码没有得到选项键 ftpAccount 的所有选项值:

public SftpFileHandler() {

    Wini ini = null;
    try {
        Config.getGlobal().setEscape(false);
        Config.getGlobal().setMultiSection(true);
        Config.getGlobal().setMultiOption(true);
        ini = new Wini(new File("MyIniFile.ini"));
    } catch (InvalidFileFormatException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    final String ftpFileNamePattern =
            ini.get("FTP", "file.pattern", String.class);
    pattern = Pattern.compile(ftpFileNamePattern);

    List<Ini.Section> list = ini.getAll("FTP_Accounts");
    final Ini.Section ftpAccountsSection = ini.get("FTP_Accounts");
    for (final String optionKey: ftpAccountsSection.keySet()) {
        System.out.println(optionKey);
    }
    ftpAccounts = ftpAccountsSection.getAll("ftpAccount", String[].class);
    final List<String> ftpAccountsList = ftpAccountsSection.getAll("ftpAccount");
    final Ini.Section sftpAccountsSection = ini.get("SFTP_Accounts");
    sftpAccounts = sftpAccountsSection.getAll("sftpAccount", String[].class);

    connect();
}

我想我可以通过 getAll 调用将所有选项值放入一个数组中。

【问题讨论】:

    标签: java arrays ini4j


    【解决方案1】:

    感谢https://stackoverflow.com/users/7345335/philippe-cerou 有问题的Java ini4j - reading multiple options from .ini file

    他指出我在实例化 Wini 对象时不要加载 ini 文件。 首先创建一个 Config 实例并将其 MultiOption 属性设置为 true。 然后初始化一个没有ini文件作为参数的Wini实例。而是在之后使用 load() 方法加载 ini 文件。

    Wini ini = null;
        Config conf = new Config();
        try {
            conf.setMultiOption(true);
            ini = new Wini();
            ini.setConfig(conf);
            ini.load(new File("MyIniFile.ini"));
        } catch (InvalidFileFormatException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-18
      • 2021-12-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-04
      相关资源
      最近更新 更多