简体   繁体   中英

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.

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.

For this kind of scenario the best approach is to add the properties file to the classpath and load it using something like ResourceBundle.

private static ResourceBundle _properties = ResourceBundle.getBundle("sample.properties");
String sampleProperty = _properties.getString(propertyKey);

How to execute :

Suppose your jar file is MyJar.jar and property file is called sample.properties then u should write a batch or sh file around it

eg: run.sh

java -cp MyJar.jar:conf "Class with main Method"

take spring's IO infrastructure (ClasspathResource)

try {
        ClassPathResource r = new ClassPathResource("bdd.properties");
        Properties properties = new Properties();
        properties.load(r.getInputStream());
    } catch (IOException e) {
        Throwables.propagate(e);
    }

this is real simplification.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM