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

前端 未结 2 1941
爱一瞬间的悲伤
爱一瞬间的悲伤 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 13:57

    The key difference is the class loader.

    The following uses the System ClassLoader
    ClassLoader.getSystemResourceAsStream("foobar.txt");

    While this one uses the Classloader returned by getClass()
    this.getClass().getResourceAsStream("/foobar.txt");

    In other words, whether both statements behave exactly the same or not, depends on the application classloader. For a simple application, both refer to the same classloader. However, for most applications (like a web application running within Servlet container), that will not be the case.

    In general, I would say getClass().getResourceAsStream() will be the better choice as it will use the same classloader as the Class the code belongs to.

提交回复
热议问题