Updating property value in properties file without deleting other values

JavaProperties

Java Problem Overview


Content of First.properties:

name=elango
country=india
phone=12345

I want change country from india to america. This is my code:

import java.io.*;
public class UpdateProperty 
{
	public static void main(String args[]) throws Exception 
	{ 	
		FileOutputStream out = new FileOutputStream("First.properties");
		FileInputStream in = new FileInputStream("First.properties");
		Properties props = new Properties();
		props.load(in);
		in.close();
		props.setProperty("country", "america");
		props.store(out, null);
		out.close();
	} 
}

Output content of First.properties:

country=america

The other properties are deleted. I want update a particular property value, without deleting the other properties.

Java Solutions


Solution 1 - Java

Open the output stream and store properties after you have closed the input stream.

FileInputStream in = new FileInputStream("First.properties");
Properties props = new Properties();
props.load(in);
in.close();
        
FileOutputStream out = new FileOutputStream("First.properties");
props.setProperty("country", "america");
props.store(out, null);
out.close();

Solution 2 - Java

You can use Apache Commons Configuration library. The best part of this is, it won't even mess up the properties file and keeps it intact (even comments).

Javadoc

PropertiesConfiguration conf = new PropertiesConfiguration("propFile.properties");
conf.setProperty("key", "value");
conf.save();    

Solution 3 - Java

Properties prop = new Properties();
prop.load(...); // FileInputStream 
prop.setProperty("key", "value");
prop.store(...); // FileOutputStream 

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionElangovanView Question on Stackoverflow
Solution 1 - JavaVasyl KeretsmanView Answer on Stackoverflow
Solution 2 - JavaAnirbanDebnathView Answer on Stackoverflow
Solution 3 - JavaJoe2013View Answer on Stackoverflow