2014-10-27 35 views
0

所以我目前得到這個方法的最後一行空指針。從我在這個問題上讀過的所有內容中,使用while ((lineIn = myReader.readLine()) != null)應該在文件沒有剩下時停止文件,但似乎沒有這樣做。相反,我最終抓住了NPE。我無法弄清楚爲什麼。任何意見,將不勝感激!我目前通過使用另一個catch (NullPointerException)聲明爲這個問題提供了創可貼,但我不認爲這是一個適當的解決方案。在EOF空指針異常

BufferedReader myReader; 

     try { 
      FileInputStream fileInStream = new FileInputStream(
        fileLocation); 
      InputStreamReader fileInputStreamReader = new InputStreamReader(
        fileInStream, "UTF-16"); 
      myReader = new BufferedReader(fileInputStreamReader); 

      String lineIn = ""; 

      // Read the next line until there aren't any left 
      while ((lineIn = myReader.readLine()) != null) { 
       //Do stuff with line 
      } 
      System.out.println("done"); 
      // Close the file connections now that the read is done. 
      fileIn.close(); 
      myReader.close(); 
     } catch (Exception e) { 
      System.out.println("Error: " + e.getMessage()); 
      e.printStackTrace(); 

}

+2

在finally塊中關閉reader:'finally {if(fileIn!= null)fileIn.close(); if(myReader!= null)myReader.close(); }' – EpicPandaForce 2014-10-27 15:59:37

+5

你在''用線做東西'裏面做什麼? – 2014-10-27 15:59:47

+1

@Zhuinden關閉'fileInStream'就足夠了。 – m0skit0 2014-10-27 16:00:37

回答

0

原來,問題是我沒有正確關閉我的文件閱讀器從以前的操作。感謝你們。

3

空指針永遠不應該被捕獲它應該被修復。您不希望它們傳播到代碼的其餘部分。

還要確保你正在關閉你的文件。添加一個finally塊並關閉這些文件資源。這樣,如果發現異常,您仍然會關閉文件。

+1

嘗試與資源(http://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html)是方法。 – Tom 2014-10-27 16:08:37

+0

是從文檔看來,似乎嘗試與資源是Java 7及以上。對於所有其他版本,最後使用try。 – Chiseled 2014-10-27 16:14:39