Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I store and retrieve Properties inside Runnable JAR?

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.

like image 307
user1562293 Avatar asked Feb 19 '23 16:02

user1562293


1 Answers

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:

  1. a directory on your machine
  2. the .jar file

Initially 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.

like image 160
Brian Agnew Avatar answered Mar 06 '23 16:03

Brian Agnew