【发布时间】:2018-06-25 22:25:54
【问题描述】:
我有一个在 Eclipse 上开发的 java 应用程序,我想生成它的可执行 jar。首先,我发现 jar 无法管理输入到FileInputStream 的路由的问题,所以我决定将FileInputStream 更改为getClass().getResourceAsStream()。问题是我必须在执行时覆盖属性文件,但 getResourceStream() 没有正确重新加载,因为它必须在缓存中或其他东西中。我尝试了在这个论坛中找到的几种解决方案,但似乎都没有。
我使用 FileInputStream 加载属性的原始代码是:
private Properties propertiesLoaded;
private InputStream input;
this.propertiesLoaded = new Properties();
this.input = new FileInputStream("src/resources/config.properties");
propertiesLoaded.load(this.input);
this.input.close();
这似乎在 Eclipse 中完美运行,但在 jar 中却不行。我用这个论坛的信息尝试了这种方法:
this.propertiesLoaded = new Properties();
this.input = this.getClass().getResourceAsStream("/resources/config.properties");
propertiesLoaded.load(this.input);
this.input.close();
问题是当程序尝试更新属性文件时,它似乎没有正确地重新加载它。我可以看到该属性已被编辑,但再次读取时它返回旧值。覆盖属性的代码是:
private void saveSourceDirectory(String str) {
try {
this.input = this.getClass().getResourceAsStream("/resources/config.properties");
propertiesLoaded.load(this.input);
propertiesLoaded.setProperty("sourceDirectory", str);
propertiesLoaded.store(new FileOutputStream("src/resources/config.properties"), null);
} catch (IOException e) {
e.printStackTrace();
}
}
我的问题是:
- 在可执行 jar 中更新属性文件的正确方法是什么?
- 如何强制我的程序重新加载属性文件中的内容?
【问题讨论】:
标签: java jar fileinputstream