getResourceAsStream() hell

后端 未结 3 523
栀梦
栀梦 2020-12-04 02:44

Can someone explain me please how .getResourceAsStream() is really working. I try to figure out the painful facts, that in some cases getClass().getResourceAsStream(name); w

3条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-04 03:32

    The rule is quite simple. Let's say your class is in the package com.foo.

    Calling getResource("bar/bla.txt") (no leading /) on this class will look for a file in bla.txt in the package com.foo.bar. The path is thus relative to the package of the class. The classpath is used to find the file, just as the classpath would be used to find a class.

    Calling getResource("/bar/bla.txt") (leading /) on this class will look for a file in bla.txt in the package bar. The path is thus an absolute path, starting at the root of the classpath. The classpath is used to find the file, just as the classpath would be used to find a class.

    And you may not have paths containing . or .. like you would have with filesystem paths.

提交回复
热议问题