Howard Wang Howard Wang - 3 years ago 162
Java Question

how to read external file from a class in the JAR

File Structure:


which is located in
wants to read

I think that both a.jar and are under the same class loader (because they are in the same web context)

I've tried the following ways to try to achieve my purpose but not work.

InputStream is = null;
ClassLoader[] loaders = { Thread.currentThread().getContextClassLoader(),
ClassLoader.getSystemClassLoader(), getClass().getClassLoader() };

ClassLoader currentLoader = null;
for (int i = 0; i < loaders.length; i++) {
if (loaders[i] != null) {
currentLoader = loaders[i];
is = currentLoader.getResourceAsStream("/META-INF/resources/");
if (is != null) { // is is always null no matter what ways I used.

I have no idea where I got mistakes.
Please guide me to the right path.
Thank you very much.


First of all , thanks for all people (especially @Ravi & @EJP) who comment, answer and discuss this question.

Below are what I've tried based on the discussion.

InputStream is = null;
URL url = getClass().getProtectionDomain().getCodeSource().getLocation();
is = A.class.getClassLoader().getResourceAsStream(url.getPath() + "../../../META-INF/resources/b.properites"); // is = null
is = new FileInputStream(url.getPath() + "../../../META-INF/resources/b.properites"); // is != null

It seems that I should use
to get resources outside of the JAR instead of using

Answer Source

It seems that I should use FileInputStream to get resources outside of the JAR instead of using getResourceAsStream()?

Resources are in the JAR file, by definition. Anything outside it is not a resource but a file, and you should use FileInputStream or FileReader to read it. You can use

URL url = getClass().getProtectionDomain().getCodeSource().getLocation();

to get the location of the JAR file, so if you distribute the file in the same directory you just have to do a little path-mangling to get the path of the file from it.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download