Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
489 views
in Technique[技术] by (71.8m points)

java - How to overwrite one property in .properties without overwriting the whole file?

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();
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


Other Answers have suggested the following approach in various guises:

  1. Load properties from file into Properties object.
  2. Update Properties object.
  3. Save Properties object on top of existing file.

This works for some use-cases. However the load / save is liable to reorder the properties, remove embedded comments and white space. These things may matter1.

The other point is that this involves rewriting the entire properties file, which the OP is explicitly trying to avoid.


1 - If the API is used as the designers intended, property order, embedded comments, and so on wouldn't matter. But lets assume that the OP is doing this for "pragmatic reasons".


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...