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?
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With