Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where does leading slash ("/") in java class loader getResource leads to?

Tags:

java

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?

like image 233
Vitali Melamud Avatar asked Dec 20 '17 07:12

Vitali Melamud


1 Answers

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.

like image 57
Michal Kordas Avatar answered Sep 18 '22 16:09

Michal Kordas