Reputation: 7476
What is the uniform or standard way to locate and then access files inside and outside JAR files.
I have InJarClass() defined in JAR file which contains configuration text files. Then I extend this class in my host project which have more configurations.
Let say I have inside the JAR :
config/default.conf
Then in the host project I do :
class MyClass extends InJarClass { .... }
and also :
config/test.conf
then I run it something like this :
XENV=test java myclass
The whole configuration process happens inside InJarClass(), based on environment XENV. As you see InJarClass() have to access both :
<jar>/config/default.conf
<host_app_dir>/config/test.conf
So to repeat my question is there uniform way to access both, if the directory structure mirror each other.
Upvotes: 0
Views: 135
Reputation: 44328
If you place both the current directory and the .jar file in your classpath:
XENV=test java -classpath .:myjarfile.jar MyClass
you can do this:
String configFile =
"/config/" +
System.getenv().getOrDefault("XENV", "default") +
".conf";
InputStream config = MyClass.class.getResourceAsStream(configFile);
if (config == null) {
throw new FileNotFoundException(
"Cannot locate " + configFile + " in classpath");
}
This works because an application resource is a resource which Java searches for within each location in the classpath. So getResourceAsStream will first search for the requested path relative to the first classpath location, .
. If it does not find a file with that name, it will look at the second classpath location, myjarfile.jar
, and seeing that it is a .jar file, will search for the requested file inside that .jar.
Upvotes: 1