简体   繁体   中英

Classpath resource within jar

I have a project A, which contains some java files and a classpath resource R.txt. Within the project I use ClassLoader.getSystemResource("R.txt"); to retrieve R.txt.

Then I have a project B which includes project A's jar-file. Now getSystemResource("R.txt") wont find the textfile (and yes, it's still in the root of the jar file). Even trying "/R.txt" as was suggested on some other site didn't work. Any ideas?

Use getResource instead of getSystemResource to use a resource specific to a given classloader instead of the system. For example, try any of the following:

URL resource = getClass().getClassLoader().getResource("R.txt");
URL resource = Foo.class.getClassLoader().getResource("R.txt");
URL resource = getClass().getResource("/R.txt");
URL resource = Foo.class.getResource("/R.txt");

Note the leading slash when calling Class.getResource instead of ClassLoader.getResource ; Class.getResource is relative to the package containing the class unless you have a leading slash, whereas ClassLoader.getResource is always absolute.

Apparently your JAR is not loaded by the system classloader, so getSystemResource() can't work. This should work:

ClassFromProjectA.class.getClassLoader().getResource("R.txt")

IMO more convenient is putting resources inside the same package as the classes that use them, so you can use the shorter

ClassFromProjectA.class.getResource("R.txt")

(or, inside that class just getClass().getResource("R.txt") )

Does ClassLoader.getResource() work ? At the moment you're simply specifying that the system classloader is to be used.

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