NullPointerException when reading a properties file in Java

前端 未结 11 1399
我在风中等你
我在风中等你 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:18

    Many seem to have this problem and like me they give up after sometime. Here is what I had to get this working. The trick here to use relative path for file lookup is to make sure your classes folder contains resources files along with src files. Here is what I ended up doing.

    1) If you are using eclipse make sure you proper .classpath setting present and do PROJECT CLEAN to see the resources files get generated under /classes. Notice the classpath-entries below for resource files place under src/main/resource

    
    
        
        
        
        
        
        
        
    
    

    2) If you are using maven as well make sure you configure your pom.xml as per the https://maven.apache.org/guides/introduction/introduction-to-the-pom.html and do mvn clean install to see the files under target/classes

    3) Once you have got the resource files under /classes the next thing to do in java is the following. Don't forget to have the forward slash.

    try {
                properties.load(getClass().getResourceAsStream("/mail-config.properties"));
            } catch (IOException e) {
                e.printStackTrace();
            }
    

    I could have added some images but did not have points. :)

提交回复
热议问题