一个更好的类来更新属性文件? [英] A better class to update property files?

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

问题描述

虽然 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 place?

推荐答案

它并没有比 Apache 的 Commons 好多少 配置 API.这提供了从属性文件、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.

它对属性文件的处理非常好.它允许您从您的财产中生成一个 PropertiesConfigurationLayout 对象,该对象保留了有关尽可能使用您的属性文件(空格、注释等).当您保存对属性文件的更改时,这些更改将尽可能保留.

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));
    }
}

另见:

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆