是否可以在运行时设置属性文件中的值.
我尝试了这个,它在读取属性的同时发生了变化,但是当我在文件中检查到没有反映出变化时.
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();
}
Run Code Online (Sandbox Code Playgroud)
输出:123.
我需要有一个属性文件应用程序,并通过GUI网页配置可以更改.
我认为问题的一部分是每次运行该代码时都要覆盖当前存在的文件.您需要做的是将当前存在的属性加载到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();
}
}
}
Run Code Online (Sandbox Code Playgroud)
首次运行后的结果:
#This is an optional header comment string
#Thu Feb 28 13:04:11 CST 2013
ServerPort=8080
ServerAddress=DullDefault
ThreadCount=456
Run Code Online (Sandbox Code Playgroud)
第二次运行(以及每次后续运行)后的结果:
#This is an optional header comment string
#Thu Feb 28 13:04:49 CST 2013
ServerPort=8080
ServerAddress=ThatNewCoolValue
ThreadCount=456
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
21655 次 |
| 最近记录: |