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?
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.
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