非常糾結的查找錯誤的過程。

剛剛寫了一個Dao類,用來完成對一個xml文件的讀寫操作。

可是在測試的時候,發現一個錯誤,這個錯誤叫做NullPointException.


但是在幾次修改之後,我發現測試通過,但是在console下又輸出上面的錯誤。可能是剛學JAVA的原因,我急着想知道自己測試的結果。於是就去尋找對應的XML文件,發現XML文件並沒有完成我需要的add操作。


我又糾結了。

於是我又去運行,最後將代碼定位到

Document document = reader.read(new File(filepath));


這行。

我當時覺得問題可能是出在filepath是無效路徑上,(我絲毫沒想到,如果filepath是無效的路徑,那麼拋出的異常會是不相同的異常。

於是,我不知道如何確定是不是這個filepath的問題。

開始,我想通過創建一個文件輸入流,然後將filepath對應的文件的文件內容輸出到控制檯。

創建之後,又告訴我是如上的NullPointException異常。


我開始看這個函數的提示,有如下的信息,英語很差的我,也勉強能夠看懂這上面的內容。


Creates a file output stream to write to the file with the specified name. A new FileDescriptor object is created to represent this file connection.

First, if there is a security manager, its checkWrite method is called with name as its argument.

If the file exists but is a directory rather than a regular file, does not exist but cannot be created, or cannot be opened for any other reason then a FileNotFoundException is thrown.

Parameters:
name the system-dependent filename
Throws:
FileNotFoundException - if the file exists but is a directory rather than a regular file, does not exist but cannot be created, or cannot be opened for any other reason
SecurityException - if a security manager exists and its checkWrite method denies write access to the file.
See Also:
java.lang.SecurityManager.checkWrite(java.lang.String)


這裏其實可以得到一條信息,如果對應的路徑沒有對應的文件,虛擬機會自動創建一個文件,而不會出現問題。

但是這個時候,我依舊執迷不悟,我一直都認爲錯誤是在路徑出現了錯誤。

這種認定了就難以改正的思路必須要改正,狠狠的改正。



最後,我發現我的路徑名是通過如下的方式獲取的。

filepath = XmlUtils.class.getClassLoader().getResource("user.xml").getPath();
//        filepath = "D://java/userloginApp/src/user.xml";


於是,我自己直接使用System.out.println(filepath);

然後進行測試,發現輸出的值爲null;


這個時候,我明白了引發問題的原因,但是依舊不知道爲什麼是null;

於是,我就通過加上filepath = "D://java/userloginApp/src/user.xml";

這條語句進行測試,發現結果依然是空。


顯然,這條語句沒有被執行。

於是,我終於發現了一個重大的問題。

static
    {
        filepath = XmlUtils.class.getClassLoader().getResource("user.xml").getPath();
//        filepath = "D://java/userloginApp/src/user.xml";
    }


 我忘記了加static這個關鍵字,所以,這兩條語句都不會執行。。。

我一下子暈了。


從頭到尾,這裏花費我的時間將近一個小時。結果找到的問題確實如此一個錯誤。這實在讓人心痛。


總結兩點吧:

1,檢查的時候,一定要注意是什麼異常,可能會因爲什麼情況發生。

2,你想到的不一定是對的,要隨時準備放棄自己的想法,不要苦苦的堅持。




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章