Confused about java properties file location

user613114 picture user613114 · Feb 5, 2012 · Viewed 42.1k times · Source

I have simple java project with structure:

package com.abc: a.java b.java c.properties

I have database configuration parameters configured in c.properties file. Inside a.java and b.java, I am loading properties file using:

Properties p = new Properties();
InputStream in = this.getClass().getResourceAsStream("c.properties");
p.load(in);

This works fine. But the main question is, once I prepare executable jar by exporting this code, properties file also gets packaged in jar file. If someone else wants to modify properties file for different database configuration, how can he do it? Do I have to store properties file in some fixed location in local machine. e.g. "c:/". Then give jar along with properties file to the other person. Then he needs to copy properties file inside C:/ location? Also one more question, how can i make this location generic for windows and linux machine?

Answer

Perception picture Perception · Feb 5, 2012

The typical way of handling this is to load the base properties from your embedded file, and allow users of the application to specify an additional file with overrides. Some pseudocode:

Properties p = new Properties();
InputStream in = this.getClass().getResourceAsStream("c.properties");
p.load(in);

String externalFileName = System.getProperty("app.properties");
InputStream fin = new FileInputStream(new File(externalFileName));
p.load(fin);

Your program would be invoked similar to this:

java -jar app.jar -Dapp.properties="/path/to/custom/app.properties"