I have a simple structure: A data jar file which contains a batch of data, and a service jar file, which runs a service using the data. To make the data easy to replace, I have them separate, and service.jar's classpath contains the directory which data.jar is in.
Within service.jar, I use getResource to load the data files. This works if the data files are directly within the folder, but fails when they are inside data.jar;
This fails:
all
+ globalclasspath
| + data.jar
| + mine.properties
+ daemons
+ service.jar
jsvc -cp globalclasspath:daemons/service.jar (...)
MyClass.class.getClassLoader( ).getResource( "mine.properties" ); // <-- null
But this works:
all
+ globalclasspath
| + mine.properties
+ daemons
+ service.jar
jsvc -cp globalclasspath:daemons/service.jar (...)
MyClass.class.getClassLoader( ).getResource( "mine.properties" ); // <-- not null
I don't want to change the classpath (unless I can change it to something generic which doesn't depend on the name of the data jar file), but I'm fine with changing the getResource string (I've tried /data/mine.properties and /data.jar/mine.properties to no avail). Is there a change I can make so that the resources can be loaded from within the jar?
Have you tried
getResourceAsStream
as suggested here:how-to-a-read-file-from-jar-in-java
Solution 1
Use a classpath wildcard.
See "How to use a wildcard in the classpath to add multiple jars?"
Solution 2
To read data in JARs not on the classpath, use
URLClassLoader
. The general algorithm is this:globalclasspath
directory.URLClassLoader
from this list of JARs.URLClassLoader
instance.To find JARs on the classpath, I used
ResourceList
from the StackOverflow article "Get a list of resources from classpath directory."I ran the following command:
The terminal output: