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

碰到一个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

学习是最好的投资!

全部回覆(3)
小葫芦

空指標異常,看看是不是23行有變數初始化為空或沒有初始化!

洪涛

1、Demo.class.getClassLoader().getResourceAsStream(),資源設定檔放在專案CLASSPATH路徑下,載入時直接給檔案名稱;

2、或使用java.util.ResourceBundle類別載入資源設定檔;

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

出現空指針異常是因為上面讀取資源檔案的語句回傳的是空指針,也就是沒有正確的定位到資源檔案(路徑錯誤)

建議題主弄清楚Demo.class.getResourceAsStream()Thread.currentThread().getContextClassLoader().getResourceAsStream()定位的路徑。再次遇到這類問題就能迎刃而解了。

試輸出以下三個語句,其中第三個語句跟Thread.currentThread().getContextClassLoader()類似

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

第一個語句得到的是Demo類所在的絕對路徑,第二、第三個語句得到的是項目CLASSPATH的絕對路徑。題主你寫的那兩個讀取資源的語句就是定位到以下路徑 项目CLASSPATH/project/db.properties,看看你的資源檔案是不是在那個地方。

熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板