Difference between ClassLoader.getSystemResourceAsStream and getClass().getResourceAsStream()

前端 未结 2 1936
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-02-14 13:05

Given this code:

/* 1 */ InputStream in1 = ClassLoader.getSystemResourceAsStream(\"foobar.txt\");
/* 2 */ InputStream in2 = this.getClass().getResourceAsStream(\         


        
2条回答
  •  抹茶落季
    2021-02-14 14:01

    According to the javadoc

    Open for reading, a resource of the specified name from the search path used to load classes. This method locates the resource through the system class loader (see getSystemClassLoader()).

    The classloader used to load this is not necessarily the system classloader. In a simple desktop app, this will probably be true. But webapps - amongst other things - typically have more complex classpath hierarchies and so that won't necessarily be the same. In a complex classpath, therefore what's returned will also depend on how many copies of 'foobar.txt' are floating around your classpath.

    The short answer is that you can't assume that they will return a stream for the same resource.

提交回复
热议问题