setting value inside property file at run time

java, properties

Solution

I think part of the problem is that you are overwriting the currently existing file every time you run that code. What you need to do is load the properties that currently exist into the Properties object, and then change the values of the properties that need changing, and finally store those properties. Something like this:

OutputStream out = null;
        try {

            Properties props = new Properties();

            File f = new File("myApp.properties");
            if(f.exists()){

                props.load(new FileReader(f));
                //Change your values here
                props.setProperty("ServerAddress", "ThatNewCoolValue");
            }
            else{

                //Set default values?
                props.setProperty("ServerAddress", "DullDefault");
                props.setProperty("ServerPort", "8080");
                props.setProperty("ThreadCount", "456");

                f.createNewFile();
            }



            out = new FileOutputStream( f );
            props.store(out, "This is an optional header comment string");

            System.out.println(props.get("ServerPort"));

       }
        catch (Exception e ) {
            e.printStackTrace();
        }
        finally{

            if(out != null){

                try {

                    out.close();
                } 
                catch (IOException ex) {

                    System.out.println("IOException: Could not close myApp.properties output stream; " + ex.getMessage());
                    ex.printStackTrace();
                }
            }
        }

Results after first run:

  #This is an optional header comment string
  #Thu Feb 28 13:04:11 CST 2013
  ServerPort=8080
  ServerAddress=DullDefault
  ThreadCount=456

Results after second run (and each subsequent run):

  #This is an optional header comment string
  #Thu Feb 28 13:04:49 CST 2013
  ServerPort=8080
  ServerAddress=ThatNewCoolValue
  ThreadCount=456

Problem

is it possible to set the value inside property file at runtime. I tried this and it changes while reading property back, but when I check in file that changes are not reflected. ``` try { Properties props = new Properties(); props.setProperty("ServerAddress", "ee"); props.setProperty("ServerPort", "123"); props.setProperty("ThreadCount", "456"); File f = new File("myApp.properties"); OutputStream out = new FileOutputStream( f ); props.store(out, "This is an optional header comment string"); System.out.println(props.get("ServerPort")); out.close(); } catch (Exception e ) { e.printStackTrace(); } ``` output: 123. my need is to have one property file application wide and through GUI web page that configuration can be change.

Original source