在运行时在属性文件中设置值

时间:2012-11-21 20:35:07

标签: java properties

是否可以在运行时设置属性文件中的值。

我尝试了这个并且在读取属性时它会发生变化,但是当我在文件中检查到没有反映出更改时。

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

输出: 123。

我需要一个属性文件应用程序,并通过GUI网页可以更改配置。

1 个答案:

答案 0 :(得分:5)

我认为问题的一部分是每次运行该代码时都要覆盖当前存在的文件。您需要做的是将当前存在的属性加载到Properties对象中,然后更改需要更改的属性的值,最后存储这些属性。像这样:

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

首次运行后的结果:

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

第二次运行(以及每次后续运行)后的结果:

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