我有一个在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中更新属性文件的正确方法是哪种?
如何强制程序重新加载属性文件上的内容?

最佳答案

对于第一个问题:您不应该这样做。一种常见的方法是在可执行jar中使用内置配置,并可以选择将配置文件作为参数传递。将配置的更改存储回jar中不是一个好主意,因为这意味着修改正在运行的二进制文件。

第二个问题:实现这种功能的常用方法是将更改侦听器添加到配置文件中。这可以使用java.nio.file package来完成:
https://docs.oracle.com/javase/tutorial/essential/io/notification.html

10-06 14:39
查看更多