【问题标题】:Apache Commons Configuration : read a .properties file and rewrite it with no changeApache Commons 配置:读取 .properties 文件并在没有更改的情况下重写它
【发布时间】:2015-10-16 06:48:40
【问题描述】:

由于我不知道更好的解决方案,我目前正在编写小型 Java 类来处理 .properties 文件以合并它们、删除重复属性、覆盖属性等(我需要处理许多文件和大量属性)。

org.apache.commons.configuration.PropertiesConfiguration 非常适合读取属性文件(使用 org.apache.commons.configuration.AbstractFileConfiguration.load(InputStream, String),但是如果我使用 org.apache.commons 重写文件.configuration.AbstractFileConfiguration.save(File),我有两个问题:

  1. 原始布局和 cmets 丢失。我将尝试 PropertiesConfigurationLayout,它应该在这里有所帮助(请参阅How to overwrite one property in .properties without overwriting the whole file?)并发布结果
  2. 属性稍作修改。重音 é 和 è 被重写为 unicode 字符 (\u00E9),这是我不想要的。 Afaik .properties 文件通常是 ISO-8859-1(我认为我的文件是),因此不需要转义。 调用 org.apache.commons.configuration.AbstractFileConfiguration.load(InputStream, String) 时指定编码并没有什么区别,因为不指定时,无论如何默认使用相同的编码(private static final String DEFAULT_ENCODING = " ISO-8859-1";)。我该怎么办?

【问题讨论】:

  • 我无法重现数字 1,如果我覆盖加载的文件,它包含具有相应覆盖属性的相同布局,以及使用您提到的 PropertiesConfigurationAbstractFileConfiguration 相同类的新布局。在 2 号我有同样的问题。
  • 如果您关注source code,您会发现保存时不使用 DEFAULT_ENCODING(这是一个内部类和抽象的网络)。我只能看到 AbstractFileConfiguration.save(OutputStream out, String encoding) 使用指定的实际编码,所有其他方法似乎最终都使用平台默认编码。你可能想试试 Ini4j 的Options

标签: java apache-commons


【解决方案1】:

做一些测试我认为你可以做你想做的事,使用CombinedConfiguration加上OverrideCombiner。基本上属性将被自动合并,布局的技巧是从加载的文件之一中获取布局:

CombinedConfiguration props = new CombinedConfiguration();

final PropertiesConfiguration defaultsProps = new PropertiesConfiguration(new File("/tmp/default.properties"));
final PropertiesConfiguration customProps = new PropertiesConfiguration(new File("/tmp/custom.properties"));
props.setNodeCombiner(new OverrideCombiner());
props.addConfiguration(customProps); //first should be loaded the override values
props.addConfiguration(defaultsProps); // last your 'default' values

PropertiesConfiguration finalFile = new PropertiesConfiguration();   
finalFile.append(props);
PropertiesConfigurationLayout layout = new PropertiesConfigurationLayout(finalFile, defaultsProps.getLayout()); //here we copy the layout from the 'base file'
layout.save(new FileWriter(new File("/tmp/app.properties")));

编码的问题不知道能不能找到解决办法。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-04-12
    • 2016-04-14
    • 2011-03-10
    • 2012-01-28
    • 2018-01-02
    • 2020-11-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多