【发布时间】:2009-11-02 06:03:18
【问题描述】:
我正在编写用于生产监控的独立 Java 应用程序。一旦它开始运行,API 就会配置为在 .properties 文件中设置的默认值。在运行状态下,可以更改 api 的配置,并相应地更新 .properties 文件。有没有办法做到这一点?还是有其他方法可以实现这一点?
提前致谢
【问题讨论】:
标签: java
我正在编写用于生产监控的独立 Java 应用程序。一旦它开始运行,API 就会配置为在 .properties 文件中设置的默认值。在运行状态下,可以更改 api 的配置,并相应地更新 .properties 文件。有没有办法做到这一点?还是有其他方法可以实现这一点?
提前致谢
【问题讨论】:
标签: java
Java 属性类 (api here) 指定了“加载”和“存储”方法,它们应该可以做到这一点。使用 FileInputStream 和 FileOutputStream 指定要保存的文件。
【讨论】:
您可以使用基于 java.util.Properties 类的非常简单的方法,该类确实具有 load 和 store 方法,您可以将它们与 FileInputStream 和 FileOutputStream 结合使用:
但实际上,我建议使用现有的配置库,例如 Commons Configuration(以及其他)。查看Properties Howto,了解如何使用其 API 加载、保存和自动重新加载属性文件。
【讨论】:
我完全同意 Apache Commons Configuration API 确实是不错的选择。
此示例在运行时更新属性
File propertiesFile = new File(getClass().getClassLoader().getResource(fileName).getFile());
PropertiesConfiguration config = new PropertiesConfiguration(propertiesFile);
config.setProperty("hibernate.show_sql", "true");
config.save();
来自how to update properties file in Java的帖子
希望对您有所帮助!
【讨论】:
据我所知,java.util.Properties 不提供开箱即用的运行时重新加载。 Commons Configuration 支持在运行时重新加载配置。重载策略可以通过setting a ReloadingStrategy on the PropertiesConfiguration object进行配置。它还提供了各种其他有用的实用程序来使您的应用程序可配置。
【讨论】:
除了Properties 类的load 和store 方法外,您还可以使用Apache Commons 配置库,它提供了轻松操作配置文件(而不仅仅是.properties 文件)的功能。
【讨论】:
Apache 通用配置 API 提供了不同的策略来在运行时重新加载属性文件。 FileChangedReloadingStrategy 就是其中之一。请参阅此link 以查看在运行时使用 FileChangedReloadingStrategy 重新加载属性文件的示例。
【讨论】:
试试这个:
// 运行时写入属性文件
public void setValue(String key, String value) {
Properties props = new Properties();
String path = directoryPath+ "/src/test/resources/runTime.properties";
File f = new File(path);
try {
final FileInputStream configStream = new FileInputStream(f);
props.load(configStream);
configStream.close();
props.setProperty(key, value);
final FileOutputStream output = new FileOutputStream(f);
props.store(output, "");
output.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
// 读取同一个文件
public String getValue(String key) {
String value = null;
try {
Properties prop = new Properties();
File f = new File(directoryPath+"/src/test/resources/runTime.properties");
if (f.exists()) {
prop.load(new FileInputStream(f));
value = prop.getProperty(key);
}
} catch (Exception e) {
System.out.println("Failed to read from runTime.properties");
}
return value;
}
【讨论】: