解析错误出现在ini文件中'#'行后

3

我有一个本地存储的 ini 文件,我正在尝试按照以下方式解析:

Ini ini = new Ini(new File("path/to/file")); 
System.out.println(ini.get("header", "key"));

但是我一直收到一个解析错误异常消息,指向 ini 文件注释行(#)后面的行。这就是我的 ini 文件的样子:

File.ini

#Tue Oct 11 18:45:03 CST 2016
PVIDNO=PALMUS-00001
PVIDNo=SSI-1
Authentication=VALID
ModelNo=KD03816-B001
PALMUS-ID=73364
PV-ID=PALMUS-01


1
Ini这个类从哪里来的?这不是Java标准库中的一个类。通常你会使用Properties类来加载这种格式的文件。 - Jesper
@Jesper忘了提到我在这方面使用ini4j。 - Kylie Irwin
看这个点击我,希望能有所帮助。 - BottleMan
3个回答

2
您正在使用来自不知道哪里的一些类Ini,而该Ini-File解析器简单地不喜欢包含“#注释”条目的.ini文件。因此,您的选择基本上是:
  1. 我先忘记这个选项,但也许是“最好”的选项:不使用“ini”文件;而改用“property”文件;这是Java应用程序的更加“自然”的选择。它们内置了对它们的支持;并且嘿,“# comments”可以直接使用。
  2. 如果Ini是“您自己的代码”,则使您自己的代码接受此类注释
  3. 如果Ini来自某个库,则检查该库是否允许影响解析过程以允许此类注释。
如果库不允许进行特殊处理,您还有两个选择:
  1. 寻找其他第三方库来解析您的文件
  2. 与您当前使用的库提供者“交谈”,并说服他们以某种方式使其库适用于您。

我已经检查了库,它确实允许 # 注释。不过我会尝试你说的关于将其更改为属性的方法。谢谢! - Kylie Irwin

2
你可以用Properties做同样的事情:
 Properties p = new Properties();
 p.load(new FileInputStream("user.props"));
 System.out.println("user = " + p.getProperty("DBuser"));
 System.out.println("password = " + p.getProperty("DBpassword"));
 System.out.println("location = " + p.getProperty("DBlocation"));

这里是 .ini 文件的位置:

# this a comment
! this a comment too
DBuser=anonymous
DBpassword=&8djsx
DBlocation=bigone

我该在哪里调用或初始化ini文件呢?抱歉,我是新手。 - Kylie Irwin
p.load() 方法。 p.load(new FileInputStream("user.props")); - granmirupa

1

您尝试使用过Properties吗?

创建配置:

Properties prop = new Properties(); OutputStream output = null;

try {
        SaveSucessful = true;
    output = new FileOutputStream("config.jar");

    // set the properties value
    prop.setProperty("PVIDNO", "PALMUS-00001");

    // save properties to project root folder
    prop.store(output, null);

} catch (IOException io) {
    io.printStackTrace();
} finally {
    if (output != null) {
        try {
            output.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    }

阅读配置:
Properties prop = new Properties();
    InputStream input = null;

    try {
            LoadSucessful = true;
        input = new FileInputStream("config.jar");

        // load a properties file
        prop.load(input);

        // get the property value and print it out
        PlayerName = prop.getProperty("PVIDNO");

    } catch (IOException ex) {
        ex.printStackTrace();
    } finally {
        if (input != null) {
            try {
                input.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

这应该完美地运行。


你正在使用.jar扩展名吗?认真的吗? - fabian
将尝试使用Properties。不太确定.jar文件。 - Kylie Irwin
使用任何你喜欢的扩展名,.jar 只是我用的一个例子。 - Mine Rockers
Kylie Irwin,如果你不知道的话,你可以点击复选标记来标记适合你的答案。 - Mine Rockers

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接