-3

enter image description here

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

Sandeep Kumar
  • 2,397
  • 5
  • 30
  • 37
  • 2
    Please include the code as text in your question, instead of as an image. Note that the arguments to `Class.getResourceAsStream` and `ClassLoader.getResourceAsStream` should generally be different - `Class.getResourceAsStream` gets a resource *relative to that class*. – Jon Skeet Jan 03 '20 at 13:55
  • Please, paste the source code instead of an image. Theses 2 methods use different path: relative for the class(uses the package as current folder ) and absolute for the classloader. for the class use getResourceAsStream("/yourporperties") to lookup on root. – pdem Jan 03 '20 at 14:07

2 Answers2

2

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.

user85421
  • 28,957
  • 10
  • 64
  • 87
2
  • The ClassLoader uses an absolute path; a full path. No preceding /!
  • The Class.getResource uses a relative path to the class's package folder, or an absolute path if preceded with a /.

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!

Joop Eggen
  • 107,315
  • 7
  • 83
  • 138
  • 1
    That last sentence is a very good point. I cringe whenever I see getResource or getResourceAsStream called on the result of getClass() instead of being called on a class literal like `MyApplication.class`. – VGR Jan 03 '20 at 14:54