I'm trying to use Java class Properties for saving the settings for my application between executions. Afterwards I would like to export my application into runnable JAR file and keep everything needed in this one file to provide portability. So my application has to find the properties file, load it and then save new settings into it on exit.
The loading works fine:
Properties prop = new Properties().load(this.getClass().getResourceAsStream("properties.cfg"));
But for storing I need to find the same file and overwrite it. The method Properties.store() needs an OutputStream but getResourceAsStream returns an InputStream therefore I cannot find the file and access it.
It should be always located with the *.class file. I found many solutions that work before exporting into JAR but none that would work after exporting. Thanks for any suggestions.
You can't rewrite your jar (or rather, it's complicated and not a good idea).
A preferable solution would be to read the properties from:
.jar
fileInitially location 1 wouldn't have a property file and you'd fall back to your .jar
file. When you write the properties you'd write them to the nominated directory, and then on the next read you'd read your properties from this location. This would survive restarts etc.
Note that libraries such as Apache Commons Configuration automatically support this tiered properties location mechanism and may save you some time/grief in writing your own solution.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With