简体   繁体   中英

How do I find resources in a .jar on the classpath?

If I have a collection of resource files in a directory on my classpath, I can enumerate them using ClassLoader.getResources(location) .

For example if I have /mydir/myresource.properties on the classpath, I can call the classloader's getResources("mydir") and get an enumeration of URLs containing myresource.properties .

When I pack up the exact same resources into a .jar, I don't get anything in the enumeration of URLs when I make the call. I've only replaced the folder structure with a jar containing those folders (it's a webapp, so the jar is going into /WEB-INF/lib ). I've also got a number of other calls using getResourceAsStream(location) to get other resources individually by name and they're all working fine.

What's different about enumerating resources when the resources are in a .jar?


Update - I've reproduced (ish) the behaviour outside the container. The following snippet results in the dirProperties object having keys set to the resource names in the package, but if the package is in a .jar throws a NullPointerException during the Properties.load(InputStream) method.

Properties dirProperties = new Properties();
dirProperties.load(this.getClass().getClassLoader().getResourceAsStream(location));

The same code on the container (Tomcat 5.5) throws no exception but produces an empty Properties object when the files are in a .jar.

Though I have lot of questions to ask to you to precisely suggest a solution, I can ask you to try this simple step which can help you to find the resources. I believe the class loader which you are using to find the resources is unable to find the resources. So you can try as below (more of a work around):

  1. Create a simple empty class (for instance, ResourceGetter.class)
  2. Package the class along with the other resources in the JAR. Let this class be packed at the same level of folder hierarchy as other resources. Inside JAR, for example :

    /resources/ResourceGetter.class

    /resources/myprop.properties ....

  3. Use ResourceGetter.class.getClassLoader().getResourceAsStream() or getResources() in your code where you want these resource files.

If you can access the resources, you can find the class loader which loaded it and you can there on solve your problem.

this.getClass ().getClassLoader ().getResourceAsStream(location);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM