getSystemResourceAsStream() returns null

前端 未结 3 1385
终归单人心
终归单人心 2020-12-06 02:38

Hiii... I want to get the content of properties file into InputStream class object using getSystemResourceAsStream(). I have built the sample code. It works well using

3条回答
  •  暖寄归人
    2020-12-06 03:28

    i deploy the project and run on the server,

    This sounds like a JSP/Servlet webapplication. In that case, you need to use the ClassLoader which is obtained as follows:

    ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
    

    This one has access to the all classpath paths tied to the webapplication in question and you're not anymore dependent on which parent classloader (a webapp has more than one!) has loaded your class.

    Then, on this classloader, you need to just call getResourceAsStream() to get a classpath resource as stream, not the getSystemResourceAsStream() which is dependent on how the webapplication is started. You don't want to be dependent on that as well since you have no control over it at external hosting:

    InputStream input = classLoader.getResourceAsStream("filename.extension");
    

    This is finally more robust than your initial getSystemResourceAsStream() approach and the Class#getResourceAsStream() as suggested by others.

提交回复
热议问题