13

I have a jar (foo.jar) with a file in it's root - 1.txt.

I tried to run the following command -

MyTestClass.class.getClassLoader().getResource("/1.txt");

The jar (foo.jar) was all I had in the classpath.

I expected this to work as the "/" is supposed to lead me to the root of the classpath/jar (according to other answers I've read in stackoverflow). This returns null.

But it seems that the leading "/" isn't working as expected for me.

I figured it out and it worked without the / -

MyTestClass.class.getClassLoader().getResource("1.txt") --> jar:file:/tmp/myjar.jar!/1.txt

What is the effect/purpose of leading "/" in getResouce?

4
  • 2
    There is a difference between class.getResource() (uses relative paths) and class.getClassLoader().getResource() (uses absolute paths)
    – Ferrybig
    Commented Dec 20, 2017 at 7:19
  • 7
    You're just not supposed to have a leading slash. ClassLoader.getResource() doesn't expect one. Class.getResource() does, though, because without it, it looks for the resource in the same package as the class.
    – JB Nizet
    Commented Dec 20, 2017 at 7:19
  • Are you using Java 9 modules? They alter the way that Class::getResource delegates.
    – Stephen C
    Commented Dec 20, 2017 at 7:35
  • Thanks for your clarifications! It's indeed a difference between the class and the classloader I've missed! Commented Dec 20, 2017 at 7:48

1 Answer 1

11

I expected this to work as the "/" is supposed to lead me to the root of the classpath/jar (according to other answers I've read in stackoverflow).

Leading slash works only for class.getResource() to override its default behavior. There is no leading slash concept for class.getClassLoader().getResource(), so it always returns null. IMO it should rather throw exception in that case, but fortunately this is solved in Guava's Resources.

1
  • 1
    It is true that class.getClassLoader().getResource() should not have a leading slash in Java SE, but I found it works with a leading slash in Java EE. But I don't know why. Commented May 23, 2021 at 13:59

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.