本文介绍了我们可以在运行时更新.properties文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
大家好,
如何在运行时更新.properties文件?
在该文件中我存储了数据库配置和我想在运行时更改数据库名称,数据库用户名等数据库配置。
我无法做到这一点。如果有人知道,请告诉我。
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.
推荐答案
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();
}
}
}
这篇关于我们可以在运行时更新.properties文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!