Click here to Skip to main content
15,880,905 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi All,

how to update the .properties file at runtime?
In that file I have stored database configuration and I want to change the
database configuration like database name,database user name,etc at runtime.
I am not able to do this.Please let me know if anyone knows.
Posted

Hi,
There is dedicated class in java to handle properties: java.util.Properties
Look at javadoc[^]for more information.
Here is example of use:

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

public class PropertiesTest {

  public static void main(String[] args)  {
    Properties props = new Properties();

    String propsFileName = "./src/myconfig.properties";
    try {
      //first load old one:
      FileInputStream configStream = new FileInputStream(propsFileName);
      props.load(configStream);
      configStream.close();

      //modifies existing or adds new property
      props.setProperty("connection", "new connection settings go here");
      props.setProperty("newProperty", "newValue");

      //save modified property file
      FileOutputStream output = new FileOutputStream(propsFileName);
      props.store(output, "This description goes to the header of a file");
      output.close();

    } catch (IOException ex) {
      ex.printStackTrace();
    }
  }
}
 
Share this answer
 
HI,
but if I run the same code on server it gives me error like No such file or directory.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900