getResourceAsStream() hell

后端 未结 3 506
栀梦
栀梦 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:11

    The performance is better when the resource you are searching for is in the same jar of the class.

    Ex: mypackagenumber1.jar/xsl/test.xsl and the class in mypackagenumber1.jar/com.foo/TestGetResourceAsStream("/xsl/test.xsl");

    I had performance problem when packing resources is in different jars, when the project has very packages jar.

    Ex:mypackagenumber1.jar/xsl/test.xsl and the class in mypackagenumber42.jar/com.foo/TestGetResourceAsStream("/xsl/test.xsl");

    0 讨论(0)
  • 2020-12-04 03:18

    You have to understand that it works in relation to the classpath.

    If you have a different classpath when running on eclipse as opposed to when running as a deployed version, you can get different results.

    The javadocs are quite explanatory as well.

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题