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


Solution 1:[1]

You can use PropertiesConfiguration from Apache Commons Configuration.

In version 1.X:

PropertiesConfiguration config = new PropertiesConfiguration("file.properties");
config.setProperty("somekey", "somevalue");
config.save();

From version 2.0:

Parameters params = new Parameters();
FileBasedConfigurationBuilder<FileBasedConfiguration> builder =
    new FileBasedConfigurationBuilder<FileBasedConfiguration>(PropertiesConfiguration.class)
    .configure(params.properties()
        .setFileName("file.properties"));
Configuration config = builder.getConfiguration();
config.setProperty("somekey", "somevalue");
builder.save();

Solution 2:[2]

Properties files are an easy way to provide configuration for an application, but not necessarily a good way to do programmatic, user-specific customization, for just the reason that you've found.

For that, I'd use the Preferences API.

Solution 3:[3]

I do the following method:-

  1. Read the file and load the properties object
  2. Update or add new properties by using ".setProperty" method. (setProperty method is better than .put method as it can be used for inserting as well as updating the property object)
  3. Write the property object back to file to keep the file in sync with the change.

Solution 4:[4]

public class PropertiesXMLExample {
    public static void main(String[] args) throws IOException {

    // get properties object
    Properties props = new Properties();

    // get path of the file that you want
    String filepath = System.getProperty("user.home")
            + System.getProperty("file.separator") +"email-configuration.xml";

    // get file object
    File file = new File(filepath);

    // check whether the file exists
    if (file.exists()) {
        // get inpustream of the file
        InputStream is = new FileInputStream(filepath);

        // load the xml file into properties format
        props.loadFromXML(is);

        // store all the property keys in a set 
        Set<String> names = props.stringPropertyNames();

        // iterate over all the property names
        for (Iterator<String> i = names.iterator(); i.hasNext();) {
            // store each propertyname that you get
            String propname = i.next();

            // set all the properties (since these properties are not automatically stored when you update the file). All these properties will be rewritten. You also set some new value for the property names that you read
            props.setProperty(propname, props.getProperty(propname));
        }

        // add some new properties to the props object
        props.setProperty("email.support", "[email protected]");
        props.setProperty("email.support_2", "[email protected]");

       // get outputstream object to for storing the properties into the same xml file that you read
        OutputStream os = new FileOutputStream(
                System.getProperty("user.home")
                        + "/email-configuration.xml");

        // store the properties detail into a pre-defined XML file
        props.storeToXML(os, "Support Email", "UTF-8");

        // an earlier stored property
        String email = props.getProperty("email.support_1");

        System.out.println(email);
      }
   }
}

The output of the program would be:

[email protected]

Solution 5:[5]

Please use just update file line instead using Properies e.g.

public static void updateProperty(String key, String oldValue, String newValue)
{
    File f = new File(CONFIG_FILE);
    try {
        List<String> fileContent = new ArrayList<>(Files.readAllLines(f.toPath(), StandardCharsets.UTF_8));

        for (int i = 0; i < fileContent.size(); i++) {
            if (fileContent.get(i).replaceAll("\\s+","").equals(key + "=" + oldValue)) {
                fileContent.set(i, key + " = " + newValue);
                break;
            }
        }
        Files.write(f.toPath(), fileContent, StandardCharsets.UTF_8);
    } catch (Exception e) {
        
    }
}

Solution 6:[6]

import java.io.*;

import java.util.*;

class WritePropertiesFile

{

         public static void main(String[] args) {
    try {
        Properties p = new Properties();
        p.setProperty("1", "one");
        p.setProperty("2", "two");
        p.setProperty("3", "three");

        File file = new File("task.properties");
        FileOutputStream fOut = new FileOutputStream(file);
        p.store(fOut, "Favorite Things");
        fOut.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

}

}

Solution 7:[7]

If you just want to override 1 prop why not just add parameter to your java command. Whatever you provide in your properties file they will be overrided with properties args.

java -Dyour.prop.to.be.overrided="value" -jar  your.jar

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 parsifal
Solution 3 Prateek Jain
Solution 4 rIshab1988
Solution 5 S?awek
Solution 6
Solution 7 oguz