java - 读取.properties配置文件 空指针异常
PHPz
PHPz 2017-04-18 09:16:43
0
3
1096

碰到一个properties的资源文件,读取报空指针,什么原因?
我使用下面2中方式读取,都是空指针。

Properties pro 
          = new Properties();
          pro.load(Demo.class.getResourceAsStream("/project/db.properties"));
          pro.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("project/db.properties"));

Exception:

Exception in thread "main" java.lang.NullPointerException
    at java.util.Properties$LineReader.readLine(Unknown Source)
    at java.util.Properties.load0(Unknown Source)
    at java.util.Properties.load(Unknown Source)
    at project.HashMap.Demo.main(Demo.java:23)
PHPz
PHPz

学习是最好的投资!

reply all(3)
小葫芦

Null pointer exception, check if there is a variable initialized to empty or not initialized in line 23!

洪涛

1, Demo.class.getClassLoader().getResourceAsStream(), the resource configuration file is placed in the project CLASSPATH path, and the file name is given directly when loading;

2. Or use the java.util.ResourceBundle class to load resource configuration files;

巴扎黑
Demo.class.getResourceAsStream("/project/db.properties")
Thread.currentThread().getContextClassLoader().getResourceAsStream("project/db.properties")

The null pointer exception occurs because the above statement to read the resource file returns a null pointer, that is, the resource file is not correctly located (path error).

It is recommended that the subject figure out the Demo.class.getResourceAsStream()Thread.currentThread().getContextClassLoader().getResourceAsStream()positioning path. If you encounter this kind of problem again, it will be easily solved.

Try to output the following three statements, the third statement is similar to Thread.currentThread().getContextClassLoader()

Demo.class.getResource("").getPath()
Demo.class.getResource("/").getPath()
Demo.class.getClassLoader().getResource("").getPath();

The first statement gets the absolute path of the Demo class, and the second and third statements get the absolute path of the project CLASSPATH. The two statements you wrote to read resources are located at the following path 项目CLASSPATH/project/db.properties. Check to see if your resource files are in that place.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template