簡體   English   中英

線程“main”中的異常java.lang.NullPointerException InputStreamReader

[英]Exception in thread “main” java.lang.NullPointerException InputStreamReader

Exception in thread "main" java.lang.NullPointerException
    at java.io.Reader.<init>(Unknown Source)
    at java.io.InputStreamReader.<init>(Unknown Source)
//at InputStreamReader inStream = new InputStreamReader(fis);

另外,我應該添加拋出IOException,FileNotFoundException到main還是使用try {}?

    System.out.print("Enter the filename: ");

    Scanner stdin = new Scanner(System.in);  //Keyboard input
    String fileName=stdin.nextLine();

    FileInputStream fis = null;
    try {
        fis = new FileInputStream(fileName);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } 
    InputStreamReader inStream = new InputStreamReader(fis);
    BufferedReader in = new BufferedReader(inStream);

你犯了一個經典的錯誤:捕獲異常(在這種情況下是FileNotFoundException)而不是實際從中恢復。 因此,當文件打開失敗時,您將傳遞null參數到InputStreamReader(...) ,這就是導致NPE。

另外,我應該添加拋出IOException,FileNotFoundException到main還是使用try {}?

這取決於您的要求。 您必須決定是否要將異常傳播到main (可能必須放棄),或者是否希望當前方法嘗試恢復。 例如,你可以要求一個不同的文件名......

代碼有效。 剛試了一下吧。 您輸入的文件名不得存在。

順便提一下,由於您已經使用Scanner從stdin讀取,因此您還應該使用Scanner來讀取文件。 我認為BufferedReaders有點笨拙可以使用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM