碰到一个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)
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;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()
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.