Update Specific Values in Java Properties File: Step-by-Step Guide

HOME

We want to replace the password from Admin to Admin123.

 Properties properties = new Properties();

 FileInputStream fileInputStream = new FileInputStream("src/test/resources/userCreated.properties");
 properties.load(fileInputStream);

properties.setProperty("password", "Admin123");

FileOutputStream fileOutputStream = new FileOutputStream("src/test/resources/userCreated.properties");

// store() method is used to write the properties into properties file
properties.store(fileOutputStream, "File is modified");
package org.example;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;

public class ModifyPropertiesExample {

    public static void main(String args[]) {

        // Creating properties files from Java program
        Properties properties = new Properties();

        try {
            FileInputStream fileInputStream = new FileInputStream("src/test/resources/userCreated.properties");
            properties.load(fileInputStream);
        } catch (IOException ex) {
            ex.printStackTrace();
        }

        properties.setProperty("password", "Admin123");
        try {
            FileOutputStream fileOutputStream = new FileOutputStream("src/test/resources/userCreated.properties");

            // store() method is used to write the properties into properties file
            properties.store(fileOutputStream, "File is modified");

            fileOutputStream.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}

Leave a comment