本文介绍了更新属性文件的更好的类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

虽然java.util.properties允许读写属性文件,但写入不会保留格式。这并不奇怪,因为它与属性文件无关。

Though java.util.properties allows reading and writing properties file, the writing does not preserve the formatting. Not surprising, because it is not tied to the property file.

是否存在一个PropertyFile类 - 或者某些类似的 - 保留注释和空行并更新属性值?

Is there a PropertyFile class out there -- or some such -- that preserves comments and blank lines and updates property values in in place?

推荐答案

它没有比Apache的Commons API。这提供了从Property文件,XML,JNDI,JDBC数据源等配置的统一方法。

It doesn't get much better than Apache's Commons Configuration API. This provides a unified approach to configuration from Property files, XML, JNDI, JDBC datasources, etc.

它对属性文件的处理非常好。它允许您从您的属性生成对象,该对象保留了尽可能多的信息你的属性文件尽可能(空格,评论等)。保存对属性文件的更改时,这些更改将尽可能保留。

It's handling of property files is very good. It allows you to generate a PropertiesConfigurationLayout object from your property which preserves as much information about your property file as possible (whitespaces, comments etc). When you save changes to the property file, these will be preserved as best as possible.

示例代码:

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStreamReader;

import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.PropertiesConfiguration;
import org.apache.commons.configuration.PropertiesConfigurationLayout;

public class PropertiesReader {
    public static void main(String args[]) throws ConfigurationException, FileNotFoundException {
        File file = new File(args[0] + ".properties");

        PropertiesConfiguration config = new PropertiesConfiguration();
        PropertiesConfigurationLayout layout = new PropertiesConfigurationLayout(config);
        layout.load(new InputStreamReader(new FileInputStream(file)));

        config.setProperty("test", "testValue");
        layout.save(new FileWriter("path\\to\\properties\\file.properties", false));
    }
}

参见:

  • http://mvnrepository.com/artifact/commons-configuration/commons-configuration/
  • https://commons.apache.org/proper/commons-configuration/apidocs/org/apache/commons/configuration2/PropertiesConfigurationLayout.html

这篇关于更新属性文件的更好的类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-31 01:33