【问题标题】:Apache Commons ConfigurationApache Commons 配置
【发布时间】:2020-07-15 15:50:51
【问题描述】:

我正在尝试使用 Apache Commons 读取配置文件,修改一些属性,然后保存配置文件。

这是代码sn-p

Configurations propConfig= new Configurations();
try {
    FileBasedConfigurationBuilder<PropertiesConfiguration> builder=
    propConfig.propertiesBuilder(pathToPropFile);
    propConfig.setProperty("dtv.primary.db.url","jdbc\\:oracle\\:thin\\:@localhost\\:1521\\:db");
    builder.save();
    return 0;
} catch (ConfigurationException e) {
    e.printStackTrace();
    return -1;
}

pom.xml sn-p

        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-configuration2</artifactId>
            <version>2.7</version>
        </dependency>
        <dependency>
            <groupId>commons-beanutils</groupId>
            <artifactId>commons-beanutils</artifactId>
            <version>1.9.4</version>
        </dependency>

问题是字符串"jdbc\\:oracle\\:thin\\:@localhost\\:1521\\:db" 没有在配置文件中正确转义。 所有额外的反斜杠都存在于配置文件中。 我已经阅读了所有文档,似乎上面的文档是转义特殊字符的正确方法。

Apache Documentation

如果我使用 Java 内置的属性类,字符串 "jdbc:oracle:thin:@localhost:1521:db" 会在存储后自动转义 (jdbc\:oracle\:thin\:@localhost\:1521\:db),但我必须使用 Apache 配置,否则我会丢失配置文件中的所有 cmets。

有什么建议吗?

【问题讨论】:

  • 代码无法编译:“方法 setProperty(String, String) 未定义类型配置”。

标签: java apache-commons-config


【解决方案1】:

在 .properties 文件中,您必须同时转义 \:。因此,您应该在 .properties 文件中拥有 jdbc\\\:oracle\\\:thin\\\:@localhost\\\:1521\\\:db)。

为了实现这一点,你可以将 PropertiesConfiguration 转换为 java.util.Properties 并保存,阅读时只使用公共配置。

您可以使用ConfigurationConverter 来执行此操作。

【讨论】:

    猜你喜欢
    • 2019-01-29
    • 2013-02-26
    • 2018-07-25
    • 2012-01-28
    • 2023-03-10
    • 2011-08-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多