简体   繁体   中英

Override properties file when running jar

I am trying to create a .JAR from a package that I have been working on and have run into a problem. I want a user to be able to modify the properties with which the program is run.

My package's folder structure looks like this:

├───src
│   ├───main
│   │   ├───java
(...)
│   │   └───resources
│   │           dbinterface.properties

and I want to override the dbinterface.properties file with one that the user places in the same folder as the jar (or in a ./config folder alongside it).

I have tried adding . to the classpath in the MANIFEST.MF, but that did not work, unfortunately.

I would implement such a behaviour in the property file reading method. You could first try to read the property file at the location the user could create, and fallback to the original default one if not found. Something like:

FileInputStream propFile;
try {
    propFile = new FileInputStream(new File("dbinterface.properties"));
} catch (FileNotFoundException e) {
    propFile = new FileInputStream(new File("resources/dbinterface.properties"));
}
Properties p = new Properties();
p.load(propFile);
propFile.close();

The best place to store user editable properties is the users home dir . In Java we have system independent access to the users home via System.getProperty("user.home") . This points to /home/$USER on linux and %USERPROFILE% on Windows. All other OS are also supported.

You could first try to read the property file at the location the user could create, and fallback to the original default one if not found. - Galcoholic

I would like to avoid this. - padrino

Why?

This is the best possible approach:

  • first read the properties file you delevered with you program,
  • then (try to) read the settings your user changed from new File(System.getProperty("user.home"),".myProgram/dbinterface.properties") ( which is basically the other way arount as suggested by @Galcoholic)

When using the Properties class from the JVM to load them the settings will automatically be merged.

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