Reputation: 1215
I wish to change a property value inside a property file. I tried some ways, such as FileInputStream/FileOutputStream or Apache's library, but all of them alter the file structure.
The structure of my file is:
#[Section 1]
prop1=value1
prop2=value2
#[Section 2]
prop2=value2
prop4=value4
After executing the code, the property changes, but "section" items disappear, and file only consists of a list of unordered properties.
Is there a way to preserve the structure above?
I TRIED THESE WAYS: Updating property value in properties file without deleting other values
Upvotes: 0
Views: 5265
Reputation: 106
I have used apache commons-configuration and it's worked fine:
PropertiesConfiguration conf = new PropertiesConfiguration("p.properties");
conf.setProperty("prop3", "newValue");
conf.save();
The whole structure does not change.
Upvotes: 1
Reputation: 16209
For example like this:
try(InputStream is = getClass().getResourceAsStream("my.properties")) {
Properties properties = new Properties();
properties.load(is);
properties.setProperty("prop4", "CHANGED");
props.store(out);
}
Note that it is not common to write to properties files. Typically you provide a default file in your distribution and the user can alter values to configure the system. If you need to store application data, consider using the Java Preferences API.
Upvotes: 0
Reputation: 109613
Yes the entire file is rewritten. Also properties are chached (you can uncache them), and property files normally are resource files, on the class path, hence maybe packed inside a jar/war.
However it seems you have it writable and all, you can opt for an XML properties file. See the Properties API, with loadFromXML and storeToXML. This also is UTF-8 capable.
Upvotes: 0
Reputation: 3762
The general approach for changing any file is to read the contents of the file, keep the content of the file in the memory, change the content that is required and write back the entire content. If you are writing the property values directly then the sections marking would be gone. There is ofcourse one exception in the above case, if you are appending content to the end of the file. Anywhere else, you have to read the file and write the file as a whole.
Upvotes: 0