【发布时间】:2017-04-15 23:27:19
【问题描述】:
我正在尝试在 Eclipse 中的 JSF Web 应用程序项目中读取和写入包含所有服务器和数据库连接的属性文件。我正在使用 log4j 写入控制台。我的 config.properties 文件是:
dbserver=localhost
dbname=mydatabase;instance=myinstance
dbuser=myuser
dbpassword=mypassword
我将 config.properties 文件放在 webapp/WEB-INF/classes 文件夹中(这是类路径对吗?)。我已经验证它在这个特定位置正确读取文件,因为如果我删除文件,它会中断。
在我的托管 bean 中,我具有读取和写入 config.properties 文件的函数。
public void getSettings() {
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
InputStream input = classLoader.getResourceAsStream("config.properties");
Properties properties = new Properties();
try {
properties.load(input);
this.server = properties.getProperty("dbserver");
this.db = properties.getProperty("dbname");
this.user = properties.getProperty("dbuser");
this.pass = properties.getProperty("dbpassword");
logger.info("Config file successfully loaded!");
} catch (IOException e) {
logger.error("Loading Database Settings Error with " + e);
} finally {
if (input != null) {
try {
input.close();
logger.info("Closing config file...");
} catch (IOException e) {
logger.error("Error closing config file with " + e);
}
}
}
}
public void saveSettings() {
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
Properties props = new Properties();
OutputStream out = null;
try {
props.setProperty("dbserver", this.server);
props.setProperty("dbname", this.db);
props.setProperty("dbuser", this.user);
props.setProperty("dbpassword", this.pass);
URL url = classLoader.getResource("config.properties");
File file = null;
try {
file = new File(url.toURI().getPath());
} catch (URISyntaxException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// File f = new File("config.properties");
out = new FileOutputStream(file);
props.store(out, "This is an optional header comment string");
logger.info("Config file successfully saved!");
} catch (IOException io) {
logger.error("Saving configuration properties failed error with : " + io.getMessage());
} finally {
if (out != null) {
try {
logger.info("Closing config file...");
out.close();
} catch (IOException e) {
logger.error("Failed closing configuration properties file error with : " + e);
}
}
}
}
我从来没有遇到过从属性文件读取的问题,但很难写入文件。这个问题似乎已经通过指定解决了
URL url = classLoader.getResource("config.properties");
现在,如果我将服务器名称从“localhost”更改为“192.168.1.1”,即使我刷新页面或重新启动服务器,我也可以看到新信息仍然存在。但是......当我打开 config.properties 文件时,我仍然看到
dbserver=localhost
当我期待看到时
dbserver=192.168.1.1
即使文件仍然保持不变,信息似乎仍然存在于其他地方?我如何以及在哪里可以访问我的属性文件的内容以查看对其进行的更改?
【问题讨论】:
-
JSF 对以这种方式(重新)加载属性文件一无所知。所以你的问题与 jsf 无关。 “我将 config.properties 文件放在 webapp/WEB-INF/classes 文件夹中(这是类路径对吗?)。我” 不,这应该是它的结束位置。最有可能的位置在 src 文件夹中(例如,使用 maven 时为 src/main/resources)
-
非常感谢您的帮助。我还在努力消化你说的话,但它确实让我大开眼界。
标签: java eclipse properties-file