在运行时以编程方式更新配置文件

时间:2015-01-13 20:12:42

标签: java runtime

我有一个config.properties文件,我想在运行时更新(例如,如果应用程序收到某个休息调用,它会更新配置属性)。

这在java中可行吗?或者我们无法在运行时更改配置文件?

感谢

3 个答案:

答案 0 :(得分:1)

如果你使用Java的Properties类,你可以这样轻松地做到这一点:

final Properties config = new Properties();

您可以将配置文件加载到内存配置中,如下所示:

final File f = new File("config.properties");
if(!f.exists) {
    f.createNewFile();
}
final InputStream in = new FileInputStream(in);
config.load(in); //loads the config into the Properties object
in.close();

如果您希望将Properties保存回文件,则可以执行以下操作:

final OutputStream out = new FileOutputStream(f);
config.save(out, "Some config comments...");
out.close();

您可能需要将其包装在try-catch块中,但基本上就是这样。

答案 1 :(得分:1)

这是可能的,我假设您使用的是Properties API? http://docs.oracle.com/javase/7/docs/api/java/util/Properties.html

您可以使用指定store

OutputStream方法

答案 2 :(得分:0)

logback在内部使用Joran,它启用了logback来读取配置文件并在运行中更新它们#34;当他们的内容发生变化我在2011年使用过这个功能,据我所知,Joran仍然是logback的一部分。

你可以这样做:

ruleMap = new HashMap<Pattern, Action>();

SetProfileParameterAction profile = new SetProfileParameterAction();
ruleMap.put(new Pattern("*/profile"), new AddProfileAction());
ruleMap.put(new Pattern("*/profile/description"), profile );
ruleMap.put(new Pattern("*/profile/link"), profile);

SimpleConfigurator simpleConfigurator = new SimpleConfigurator(ruleMap);

simpleConfigurator.setContext(context);

try {
    simpleConfigurator.doConfigure(cfgFile);
} catch (JoranException e) {
    log.error( "failed ...", e);
    StatusPrinter.print(context);
}

请注意:这只是我的代码的一个非完整的缩减版本,但如果Joran为你工作,这个例子会给你一个提示,指示去哪个方向......

相关问题