Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Classpath resource within jar

Tags:

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?

like image 896
Johan Sjöberg Avatar asked Dec 14 '09 10:12

Johan Sjöberg


People also ask

Can jar contain resources?

jar ) contain your executable classes and resource files. A jar can also contain other jar files, which is useful when your program needs some library which is packaged in a jar.

What is a classpath resource?

A resource is file-like data with a path-like name, which resides in the classpath. The most common use of resources is bundling application images, sounds, and read-only data (such as default configuration). Resources can be accessed with the ClassLoader. getResource and ClassLoader.


1 Answers

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.

like image 104
Jon Skeet Avatar answered Oct 03 '22 12:10

Jon Skeet