Reputation: 1
I googled a lot but still don't understand Why ClassLoader.getResource("/pkg/readme.txt") always return null? otherwise without the leading slash, ClassLoader.getResource("pkg/readme.txt") can return a correct URL.
I do understand the diff between those methods in Class and ClassLoader.
NOTE: I'm not asking the diff between Class.getResource() and ClassLoader.getResource() because I get it. My concern is on ClassLoader.getResource() does not work for a resource name which starts with a leading slash
Upvotes: 2
Views: 523
Reputation: 122364
My concern is on
ClassLoader.getResource()
does not work for a resource name which starts with a leading slash
That's because there are no resource names that start with a leading slash. By definition a resource name is "a '/'-separated path name that identifies the resource" - the components are separated by slashes, not preceded by them.
someClass.getResource("/pkg/readme.txt")
is equivalent to someClass.getClassLoader().getResource("pkg/readme.txt")
, the leading slash is not part of the resource name but rather an indication to Class.getResource
that it should not prepend the class's package to the path it passes to the classloader. Without the leading slash:
someClass.getResource("pkg/readme.txt")
would be equivalent to
someClass.getClassLoader().getResource("com/example/pkg/readme.txt")
(assuming someClass
is in the package com.example
)
Upvotes: 3
Reputation: 11117
Class's getResource() - documentation states the difference:
This method delegates the call to its class loader, after making these changes to the resource name: if the resource name starts with "/", it is unchanged; otherwise, the package name is prepended to the resource name after converting "." to "/". If this object was loaded by the bootstrap loader, the call is delegated to ClassLoader.getSystemResource.
What is the difference between Class.getResource() and ClassLoader.getResource()?
Upvotes: 2