Can getResourceAsStream() find files outside the j

2019-03-27 12:17发布

问题:

I'm developing an application that uses a library that loads a configuration file as:

InputStream in = getClass().getResourceAsStream(resource);

My application in then packed in a .jar file. If resource is inside the .jar file, I can specify the path as "/relative/path/to/resource/resource".

I'd like to know if is it possible to find the resource if it is outside the .jar file, and in this case, how would I specify the path.

(Assuming my application's jar is in app/ and the resource is in app/config).


The program uses a 3rd party library. The library uses the resource as a configuration file.

I also want to tweak the configuration file without having to unzip/zip the jar file all the time.

回答1:

In general, yes it can. Technically, the class's ClassLoader is used to locate the resource named in the parameter (see Javadoc here). If you're not using a special ClassLoader then you'll get the bootstrap class loader, which searches the class path. So, if you have directories or other jar files on the classpath, they will be searched.



回答2:

It will get any resource which is available to the appropriate classloader (the one that getClass().getClassLoader() would return). Whether the classloader includes both the app directory and the jar files depends on the rest of your application context.



回答3:

There is a way to get the current directory ( How to get the path of a running JAR file?), but for configuration you can just pass a -Dconfig.location to the JVM specifying an absolute path for the configuration