如何在不覆盖整个文件的情况下覆盖.properties中的一个属性? [英] How to overwrite one property in .properties without overwriting the whole file?

查看:288
本文介绍了如何在不覆盖整个文件的情况下覆盖.properties中的一个属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基本上,我必须通过Java应用程序覆盖.properties文件中的某个属性,但是当我使用Properties.setProperty()和Properties.Store()时,它会覆盖整个文件,而不是仅覆盖那个属性。 / p>

我尝试使用append = true构建FileOutputStream,但是它添加了另一个属性,并且不会删除/覆盖现有属性。



我如何对其进行编码,以便设置一个属性会覆盖该特定属性,而不会覆盖整个文件?



编辑:我试过阅读该文件并添加到它。这是我的更新代码:

  FileOutputStream out = new FileOutputStream(file.properties); 
FileInputStream in = new FileInputStream(file.properties);
属性props = new Properties();

props.load(in);
in.close();

props.setProperty(somekey,somevalue);
props.store(out,null);
out.close();


解决方案

属性 API不提供在属性文件中添加/替换/删除属性的任何方法。 API支持的模型是从文件加载所有属性,更改内存属性对象,然后将所有属性存储到文件中(相同或不同)。



属性 API在这方面并不罕见。实际上,如果不重写整个文件,就很难实现文本文件的就地更新。这种困难是文件/文件系统由现代操作系统实现的直接结果。



如果你真的需要进行增量更新,那么你需要使用某种数据库来保存属性,而不是.properties文件。


Basically, I have to overwrite a certain property in a .properties file through a Java app, but when I use Properties.setProperty() and Properties.Store() it overwrites the whole file rather than just that one property.

I've tried constructing the FileOutputStream with append = true, but with that it adds another property and doesn't delete/overwrite the existing property.

How can I code it so that setting one property overwrites that specific property, without overwriting the whole file?

Edit: I tried reading the file and adding to it. Here's my updated code:

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

解决方案

The Properties API doesn't provide any methods for adding/replacing/removing a property in the properties file. The model that the API supports is to load all of the properties from a file, make changes to the in-memory Properties object, and then store all of the properties to a file (the same one or a different one).

But the Properties API is not unusual in the respect. In reality, in-place updating of a text file is difficult to implement without rewriting the entire file. This difficulty is a direct consequence of the way that files / file systems are implemented by a modern operating system.

If you really need to do incremental updates, then you need to use some kind of database to hold the properties, not a ".properties" file.

这篇关于如何在不覆盖整个文件的情况下覆盖.properties中的一个属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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