I have a simple java application that loads a properties file from the current package.
this.getClass().getResourceAsStream("props.properties");
This works fine when the property file I want is in the current package. However, I want to package this application as a JAR and define and override with a new properties file where I use it. Is there a way to load the first resource named "props.properties" that is on the classpath?
I want it to be as easy to override the properties file via command line:
java.exe -classpath props.properties;myJar.jar com.test.MyApp
I don't want to have to unpack the JAR and modify the properties file to change something. I feel like I'm missing something obvious...
We can either load the file(present in resources folder) as inputstream or URL format and then perform operations on them. So basically two methods named: getResource() and getResourceAsStream() are used to load the resources from the classpath. These methods generally return the URL's and input streams respectively.
A resource is file-like data with a path-like name, which resides in the classpath. The most common use of resources is bundling application images, sounds, and read-only data (such as default configuration). Resources can be accessed with the ClassLoader. getResource and ClassLoader.
In Java, we can use getResourceAsStream or getResource to read a file or multiple files from a resources folder or root of the classpath. The getResourceAsStream method returns an InputStream . // the stream holding the file content InputStream is = getClass(). getClassLoader().
1) click project -> properties -> Build Path -> Source -> Add Folder and select resources folder. 2) create your JAR!
The javadoc for Class.getResourceAsStream()
documents the lookup logic:
If the name begins with a
'/'
('\u002f'
), then the absolute name of the resource is the portion of the name following the '/'.Otherwise, the absolute name is of the following form:
modified_package_name/name
Where the
modified_package_name
is the package name of this object with '/' substituted for'.'
('\u002e'
).
So in other words, the resource name passed to the method should look like /com/package/p2/props.properties
if the props.properties
is stored in the com.package.p2
package instead of the current class's.
I'm sure it's too late for the answer but it could be interesting for googlers this small code snippet helpers to load a properties file from any where in the Classpath.
ClassLoader cl = ClassLoader.getSystemClassLoader();
if (cl != null) {
URL url = cl.getResource(CONF_PROPERTIES);
if (url == null) {
url = cl.getResource("/" + CONF_PROPERTIES);
}
if (url != null) {
try {
InputStream in = url.openStream();
props = new Properties();
props.load(in);
} catch (IOException e) {
// Log the exception
} finally {
// close opened resources
}
}
}
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