简体   繁体   中英

ClassLoader getResource() in called jar uses resources from the caller

I have two java projects. Project B is a utility, meant to be packaged as a jar and called by other projects. Project A needs to call project B. However, when project B calls ClassLoader getResource(), it is loading resources from project A. How do I get it to load from project B? It seems like this should be easy, so I feel that I must be missing something simple. The following code is in the project B, called from project A. path/to/file.txt is in the resources folder in project B.

System.out.println(Paths.get(classLoader.getResource("path/to/file.txt").toURI()).toString());

Output: C:\Users\....\projectA\target\test-classes

Normally the way you achieve this is to include path/to/file.txt as a resource in B.jar .

As an example, include Guava 19.0 as a compile time dependency in your Maven project (it looks like you're using Maven). The following code works for me:

// pom.properties is bundled in guava-19.0.jar.
URL resource = Example.class.getResource("/META-INF/maven/com.google.guava/guava/pom.properties");
System.out.println(resource.toString());

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