why ClassLoader.getResourceAsStream
can find file but Class.getResourceAsStream
can not
just like pic see.
Class.getResourceAsStream
has first getClassLoader
and then use ClassLoader.getResourceAsStream
why ClassLoader.getResourceAsStream
can find file but Class.getResourceAsStream
can not
just like pic see.
Class.getResourceAsStream
has first getClassLoader
and then use ClassLoader.getResourceAsStream
Documentation of Class.getResourceAsStream:
This method delegates to this object's class loader.
...
Before delegation, an absolute resource name is constructed from the given resource name using this algorithm:
- If the name begins with a '/' ('\u002f'), then the absolute name of the resource is the portion of the name following the '/'
- Otherwise, the absolute name is of the following form:
modified_package_name/name
Where the modified_package_name is the package name of this object with '/' substituted for '.'
that is, the difference between both methods: the package name being added.
Probably - I cannot read the image - the given file is not in the same package as the class, so it is not being found.
/
!/
.So for Class.getResourceAsStream a /
was missing in front.
The rationale is that resources for a class could be organized to be stored locally at the package of the class. A ClassLoader only knows full class paths.
Mind also that getClass().getResourceAsStream(relativePath)
might apply that relativePath to a child class!