Reputation: 1367
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:
Upvotes: 0
Views: 1740
Reputation: 837
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
Upvotes: 2
Reputation: 821
I think the only way to update a file inside jar (or zip) is extract, modify and compress it again. Probably you cant't do this with a running jar.
When you did:
propertiesLoaded.store (new FileOutputStream ("src / resources / config.properties"), null);
You probably get a FileNotFoundException because you can't use the File API, like you can't use FileInputStream to load the properties.
Probably the best solution would be store the properties somewhere outside the jar or using the Java Preferenced API.
Related: https://coderanch.com/t/616489/java/modify-Properties-file-JAR
Upvotes: 2