26 java properties fileoutputstream
基本上,我必须通过Java应用程序覆盖.properties文件中的某个属性,但是当我使用Properties.setProperty()和Properties.Store()时,它会覆盖整个文件而不是仅覆盖那个属性.
我尝试使用append = true构建FileOutputStream,但是它添加了另一个属性,并且不会删除/覆盖现有属性.
我如何对其进行编码,以便设置一个属性会覆盖该特定属性,而不会覆盖整个文件?
编辑:我尝试读取文件并添加到它.这是我更新的代码:
FileOutputStream out = new FileOutputStream("file.properties");
FileInputStream in = new FileInputStream("file.properties");
Properties props = new Properties();
props.load(in);
in.close();
props.setProperty("somekey", "somevalue");
props.store(out, null);
out.close();
Run Code Online (Sandbox Code Playgroud)
Ste*_*n C 20
该Properties
API不用于添加/更换/移除在属性文件中的属性提供的任何方法.API支持的模型是从文件加载所有属性,更改内存中Properties
对象,然后将所有属性存储到文件(相同的一个或不同的文件).
但Properties
API在这方面并不罕见.实际上,如果不重写整个文件,很难实现文本文件的就地更新.这种困难是现代操作系统实现文件/文件系统的直接结果.
如果您确实需要进行增量更新,则需要使用某种数据库来保存属性,而不是".properties"文件.
其他答案以各种形式提出了以下方法:
Properties
对象中.Properties
对象.Properties
对象保存在现有文件之上.这适用于某些用例.但是,加载/保存可能会重新排序属性,删除嵌入的注释和空格.这些事情可能很重要1.
另一点是,这涉及重写整个属性文件,OP明确试图避免.
1 -如果API被用作预期的设计师,产权制度,嵌入的注释,等等不会没关系.但我们假设OP是出于"务实的原因"这样做的.
dav*_*olo 14
您可以使用Apache Commons Configuration中的 PropertiesConfiguration .
在版本1.X中:
PropertiesConfiguration config = new PropertiesConfiguration("file.properties");
config.setProperty("somekey", "somevalue");
config.save();
Run Code Online (Sandbox Code Playgroud)
从2.0版开始:
Parameters params = new Parameters();
FileBasedConfigurationBuilder<FileBasedConfiguration> builder =
new FileBasedConfigurationBuilder<FileBasedConfiguration>(PropertiesConfiguration.class)
.configure(params.properties()
.setFileName("file.properties"));
Configuration config = builder.getConfiguration();
config.setProperty("somekey", "somevalue");
builder.save();
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
49898 次 |
最近记录: |