虽然java.util.properties允许读取和写入属性文件,但写入不会保留格式.这并不奇怪,因为它与属性文件无关.
是否有一个PropertyFile类 - 或者某些类 - 保留注释和空行并更新属性值?
Il-*_*ima 54
它没有比Apache的Commons Configuration API 好多少.这提供了从Property文件,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));
}
}
Run Code Online (Sandbox Code Playgroud)
也可以看看:
Patrick Boos提供的使用Apache Commons Configuration库的示例代码不必要地复杂化.除非需要对输出进行一些高级控制,否则不需要显式使用PropertiesConfigurationLayout.PropertiesConfiguration本身足以保留注释和格式:
PropertiesConfiguration config = new PropertiesConfiguration("myprops.properties");
config.setProperty("Foo", "Bar");
config.save();
Run Code Online (Sandbox Code Playgroud)
(注意:此代码适用于现有的1.10稳定版本.我没有检查它是否适用于当前可用的2.0 alpha版本.)
您可以查看包含PropertiesConfiguration类的Apache Commons Configuration.但是,由于我从未使用它,我不知道它是否保留了评论和格式......
然而,它试了一下......
小智 5
configuration2 类有不同的语法。这是使用它们的示例:
import org.apache.commons.configuration2.PropertiesConfiguration;
import org.apache.commons.configuration2.PropertiesConfigurationLayout;
public void test() {
PropertiesConfiguration config = new PropertiesConfiguration();
PropertiesConfigurationLayout layout = new PropertiesConfigurationLayout();
config.setLayout(layout);
layout.load(config, new FileReader("config.properties"));
config.setProperty("KEY", "VALUE");
StringWriter stringWriter = new StringWriter();
layout.save(config, stringWriter);
LOG.debug("Properties:\n{}", stringWriter.toString());
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
17255 次 |
| 最近记录: |