簡體   English   中英

線程“ main”中的異常java.lang.NumberFormatException:對於輸入字符串:Java中的“”

[英]Exception in thread “main” java.lang.NumberFormatException: For input string: “” in Java

我在Java中創建了一個類,以讀取文本文件(.txt),並在屏幕上打印結果。 腳本正在讀取文本文件的內容,但最后顯示消息:

Exception in thread "main" java.lang.NumberFormatException: For input string: ""
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:592)
at java.lang.Integer.parseInt(Integer.java:615)
at com.desafioProgramacao.LerArquivo.main(LerArquivo.java:24)

我不知道為什么它顯示消息。 在FINALLY類中,我告訴它如果文件的內容為null,則關閉FileReader和BufferedReader。 遵循Java代碼和屏幕打印。

public class LerArquivo {

private static final String NomeArquivo = "E:\\DesafioProgramacao\\matriculasSemDV.txt";

public static void main(String[] args) {

    FileReader fr = null;
    BufferedReader br = null;

    try {
        fr = new FileReader(NomeArquivo);

        br = new BufferedReader(fr);

        String sCurrentLine;

        while ((sCurrentLine = br.readLine()) != null) {
            int num = Integer.parseInt(sCurrentLine);
            System.out.println(num);
        }
    } catch (IOException e) {
        e.printStackTrace();

    } finally {

        try {
            if (br != null) {

                br.close();

            }

            if (fr != null) {

                fr.close();
            }
        } catch (IOException ex) {

            ex.printStackTrace();
        }
    }
}}

例外

文件閱讀器

表面上的原因是您讀取了一個空字符串並將其解析為int

對於代碼,您需要檢查sCurrentLine

while ((sCurrentLine = br.readLine()) != null) {
    if(StringUtils.isNotBlank(sCurrentLine)){//StringUtils is from `commons-lang` 
     // or if(sCurrentLine.length()>0)
     int num = Integer.parseInt(sCurrentLine);
     System.out.println(num);
    }
}

對於txt文件,您需要刪除文件末尾的所有空行

您的文件包含一個空行(可能在末尾)。

將您的while循環替換為:

while ((sCurrentLine = br.readLine()) != null && !sCurrentLine.isEmpty()) 

問題是最后一行,它是空白。 你可以做:

while ((sCurrentLine = br.readLine()) != null) {
    if (!sCurrentLine.isEmpty()) {
        int num = Integer.parseInt(sCurrentLine);
        System.out.println(num);
    }
}

修復它的正確方法是捕獲該NumberFormatException並正確處理它,如下所示:

         try {
            int num = Integer.parseInt(sCurrentLine);
            System.out.println(num);
        } catch (NumberFormatException ex) {
            System.out.println("Error reading line: " + sCurrentLine);
        }

暫無
暫無

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

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