gpt4 book ai didi

java - 更新属性文件的更好的类?

转载 作者:IT老高 更新时间:2023-10-28 20:53:15 26 4
gpt4 key购买 nike

虽然java.util.properties 允许读取和写入属性文件,但写入不会保留格式。不足为奇,因为它不绑定(bind)到属性文件。

是否有 PropertyFile 类 - 或类似的 - 保留注释和空行并更新属性值?

最佳答案

它并没有比 Apache 的 Commons Configuration 好多少。 API。这提供了从属性文件、XML、JNDI、JDBC 数据源等进行配置的统一方法。

它对属性文件的处理非常好。它允许您生成 PropertiesConfigurationLayout来自您的属性的对象,它尽可能多地保留有关您的属性文件的信息(空格、注释等)。当您保存对属性文件的更改时,这些更改将尽可能保留。


示例代码:

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

另见:

关于java - 更新属性文件的更好的类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/565932/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com