Updating property value in properties file without deleting other values [duplicate]
Asked Answered
A

3

59

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.

Appledorf answered 11/3, 2013 at 11:26 Comment(1)
Similar: #7462401 and #566432God
S
105

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

try (FileInputStream in = new FileInputStream("First.properties")) {
    Properties props = new Properties();
    props.load(in);
}
        
try (FileOutputStream out = new FileOutputStream("First.properties"))
    props.setProperty("country", "america");
    props.store(out, null);
}
Sitzmark answered 11/3, 2013 at 11:31 Comment(11)
Thanks Vasyl Keretsman i change code. Is it correct? Properties props = new Properties(); props.load(in); props.setProperty("country", "america"); props.store(out, null); out.close(); in.close(); but answer is same. I didn't get the expected answerAppledorf
Not correct. I have added the code to my answerSitzmark
Thank You Vasyl Keretsman. It is working ..Appledorf
@VasylKeretsman it is removed all existing comments in the fileLazurite
Closing streams should be done in a finally block/ try-with-resources statement.Edwyna
Maybe you are also interested in this Property Library. It can preserve order and comments. #566432X
Yes gr8 it solved ......... but why ?????Poeticize
How did this become the accepted answer ? It removes all previously set properties.Chenee
This answer should state that you have to rewrite all properties again. Check this answer #7462401Chenee
Those for which the code is not working. Please verify the sequence of lines with the code provided. Sequence of lines does matter here.Bezonian
It removes all the previous properties. And aslo adds the timestamp in the first line of the property file.Abroach
K
35

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();    
Kollwitz answered 4/9, 2016 at 20:44 Comment(11)
This is much better answer than the accepted oneEthnography
@José Mª I downloaded commons.apache.org/proper/commons-configuration/index.html ApacheCommons Configurator 2.1.1 and it seems that save() method and some others doesn't exists . Is there any alternative ?Valued
@Valued Please check this website: commons.apache.org/proper/commons-configuration/userguide_v1.10/… There is a "Saving" section where its explained.Ethnography
@José Mª Thanks for the link . It seems to be only for the version 1.10 , not for the version 2.1.1 which is the latest :) . I am searching inside commons.apache.org/proper/commons-configuration/userguide/… to find something similar .Valued
@Valued Sorry I can't test it right now, but I thought it should work because there is a annotation at the header of the website where you can see: "Last Published: 08 February 2017|Version: 2.1.1" It's quite confusing, but you can still use older versions. Unfortunately, I cannot help you any more with this :(Ethnography
@JoséMª I had used the 1.1 version. Also, the 2.1 version has the save() method in it. commons.apache.org/proper/commons-configuration/apidocs/org/…Kollwitz
@Kollwitz Thank you for the info, but how can that link demonstrate it? There are only 1 match with "save()" in the whole page and doesn't correspond to the method description. Where is save() hidden?Ethnography
Okay you are using the apache-commons thats causing the issue. Use the commons-configuration one. Use this: mvnrepository.com/artifact/commons-configuration/…Kollwitz
I am using commons configuration2 but getting an error when using above code `PropertiesConfiguration() in PropertiesConfiguration can not be applied to (java.lang.String)Pullet
Hi @J.Doem: You can use the Older 1.10 version which has a String args constructor to pass the file name directly. Else, for V2, you can use the PropertyConfiguration class's loadIncludeFile(String fileName) method to pass the File name.Kollwitz
This solution solved my 2 issues. 1. Saving the file without losing other data and also 2. Keys positions are not swapped (By using other solutions i.e., with FileInput & Output streams, positions of keys are getting swapped to random positions and also comments are getting removed).Hypothec
H
10
Properties prop = new Properties();
prop.load(...); // FileInputStream 
prop.setProperty("key", "value");
prop.store(...); // FileOutputStream 
Harrelson answered 11/3, 2013 at 11:39 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.