I have a java application developed on Eclipse and I wanted to generate an executable jar of it. First of all I've found the problem that the jar can not manage the route entered to a FileInputStream
so I decided to change the FileInputStream
for a getClass().getResourceAsStream()
. The problem is that I have to overwrite the properties file while executing but the getResourceStream()
is not properly reloading since it must have it in cache or something. I have tried several solutions found in this forum but none of those seem to work.
My original code to load the properties with the FileInputStream was:
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();
That seems to work perfectly from Eclipse but not from the jar. I tried this approach with info from this forum:
this.propertiesLoaded = new Properties();
this.input = this.getClass().getResourceAsStream("/resources/config.properties");
propertiesLoaded.load(this.input);
this.input.close();
The problem is that when the program tries to update the properties file it does not seem to reaload it properly. I can see that the property has been edited, but when reading again it returns the old value. The code for overriding the property is:
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();
}
}
My questions are:
For your first question: you should not do it. A common way woul be to use a builtin configuration in you executable jar with the option of passing a config file as argument. Storing changes of the configuration back into the jar is not a great idea because it means modifing the running binary.
Second question: a usual way to implement such a functionality would be to add a change listener to your config file. This can be done using the java.nio.file package
:
https://docs.oracle.com/javase/tutorial/essential/io/notification.html