碰到一个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)
空指標異常,看看是不是23行有變數初始化為空或沒有初始化!
1、
Demo.class.getClassLoader().getResourceAsStream()
,資源設定檔放在專案CLASSPATH路徑下,載入時直接給檔案名稱;2、或使用
java.util.ResourceBundle
類別載入資源設定檔;出現空指針異常是因為上面讀取資源檔案的語句回傳的是空指針,也就是沒有正確的定位到資源檔案(路徑錯誤)。
建議題主弄清楚
Demo.class.getResourceAsStream()
和Thread.currentThread().getContextClassLoader().getResourceAsStream()
定位的路徑。再次遇到這類問題就能迎刃而解了。試輸出以下三個語句,其中第三個語句跟
Thread.currentThread().getContextClassLoader()
類似第一個語句得到的是Demo類所在的絕對路徑,第二、第三個語句得到的是項目CLASSPATH的絕對路徑。題主你寫的那兩個讀取資源的語句就是定位到以下路徑
项目CLASSPATH/project/db.properties
,看看你的資源檔案是不是在那個地方。