【问题标题】:Modify Apache CommonConfiguration to not to trim values修改 Apache CommonConfiguration 以不修剪值
【发布时间】:2026-01-07 23:40:01
【问题描述】:

出于各种原因,我正在使用 Apache 通用配置库来读取属性文件。我的代码如下。默认情况下,它会去除我想要避免的值前后的空格。有没有办法做到这一点?

CompositeConfiguration config = new CompositeConfiguration();
PropertiesConfiguration propertiesConfiguration = new PropertiesConfiguration();
URL url = CommonConfig.class.getResource("samplePropertiesFile.properties");
Reader reader = new FileReader(new File(url.getFile()));
propertiesConfiguration.read(reader);
config.addConfiguration(propertiesConfiguration);

samplePropertiesFile.properties 的内容:

key=<space>value<space>  

//前后的空格都必须保留。

【问题讨论】:

    标签: java apache configuration


    【解决方案1】:

    值是 Java 转义的1,因此使用 \u0020 表示不应删除的前导和尾随空格。

    只有第一个前导和最后一个尾随空格需要这个,例如

    key  =  \u0020  value  \u0020
    

    将是字符串&lt;sp&gt;&lt;sp&gt;&lt;sp&gt;value&lt;sp&gt;&lt;sp&gt;&lt;sp&gt;

    (或)

    像“自定义属性读取器和写入器”部分中的示例一样编写 CustomPropertiesConfiguration https://commons.apache.org/proper/commons-configuration/userguide/howto_properties.html

    1) 根据source code.

    【讨论】:

    • 这是一个可能的解决方法。谢谢你。有什么办法可以保持属性文件不变,通过代码修改来解决?
    • 是的,当然有。你....eehhhhh ....更改代码!!?!?!!? 步骤1:获取源代码。第 2 步:进行更改。第 3 步:编译并构建新的 jar 文件。第 4 步:替换类路径中的 jar 文件。
    • hmmmmm... 我期待这样的事情 - commons.apache.org/proper/commons-configuration/userguide/… 上的自定义属性读取器和写入器部分,这是针对 PropertiesConfiguration,而不是 CompositeConfiguration
    • 糟糕,我错过了,我的错