NullPointerException when reading a properties file in Java

前端 未结 11 1404
我在风中等你
我在风中等你 2020-12-09 17:05

I am using the following code to read a properties file:

Properties pro = new Properties();
InputStream is = Thread.currentThread().getContextClassLoader().         


        
11条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-09 17:22

    I had the same problem and was quite confused as I used it previously in a Sturts application. But the problem was that I didn't understand the type of ClassLoader that Struts returns is different than what Spring returns. And the way i figured it out was i printed out the object that was returned on to the system console like this:

    System.out.println(Thread.currentThread().getContextClassLoader());
    

    [
    WebappClassLoader
    context: /MyProject
    delegate: false
    repositories:
    /WEB-INF/classes/
    ----------> Parent Classloader:
    org.apache.catalina.loader.StandardClassLoader@1004901
    ]

    It gave me the detail of the object, and in that I found its type to be of WebAppClassLoader which will start looking for files in the WEB-INF/classes/ folder after a build is done. So I went into the that folder and looked for where my file is located so I gave the path accordingly.

    In my case it was located in /WEB-INF/classes/META-INF/spring/filename.extension

    InputStream in = Thread.currentThread().getContextClassLoader().getResourceAsStream("META-INF/spring/filename.extension");
    

    Voilà!

    That fixed it all.

提交回复
热议问题