读取输入时抛出Java异常

时间:2014-08-16 10:26:09

标签: java

我正在使用ScannerFileReader从Java中的.txt文件中读取一组整数值。输入文件中每行有一个值。所有值都被读入StringBuilder变量,但由于某种原因,编译器在读取while循环中的输入结束时抛出异常,我无法弄清楚原因。

    Scanner inFile;
    String value = "";
    String arrayString = "";
    StringBuilder sb = new StringBuilder();
    try {
        inFile = new Scanner(new FileReader("data.txt"));
        value = inFile.next();
        while (inFile.hasNextLine()) {
            sb.append(value);
            value = inFile.next();
        }

        arrayString = sb.toString(); // Not executing
        System.out.println(arrayString); // Not executing
        inFile.close();

    } catch (Exception e) {
        System.out.println("Error: File not found.");
    } finally {
        // inFile.close();
    }
    System.out.println(arrayString); // Not executing

3 个答案:

答案 0 :(得分:1)

  

编译器在读取while循环中的输入结束时抛出异常

编译器没有"抛出异常"。相反,它会提供与代码本身问题相关的错误/警告。

说完这个,"在阅读输入结束时"暗示您的文件可能包含整数值集后面的换行符。如果是这种情况,则Scanner会在致电java.util.NoSuchElementException时抛出value = inFile.next();

您可以尝试以下阅读方式:

while (inFile.hasNextLine()) {
    value = inFile.nextLine();
    sb.append(value);
}

还尝试在catch块中打印异常消息。 java.util.NoSuchElementException并不代表Error: File not found.

答案 1 :(得分:0)

我用1到6的整数创建了文件,相同的代码工作正常。 如果最后一行没有空格。 但是如果我将最后一行保留为空格或空格,那么它将进入异常。 只是检查,是你的最后一行data.txt文件有空格吗?

答案 2 :(得分:0)

好吧,您可能会在FileNotFoundException

上获得inFile = new Scanner(new FileReader("data.txt"));

使用扫描仪阅读文件时,您也可能会遇到几个例外情况。您正在捕捉Exception所以一切都将被捕获。

现在的行:

arrayString = sb.toString(); // Not executing
System.out.println(arrayString); // Not executing
inFile.close(); // --> Is also not executed. Resource leak here. put it in finally.

try{}块之外,因此,它们不会被执行。 抓住{} gets executed because you have an exception and终于{}`被执行总是

因此,System.out.println(arrayString);超出try{} , catch{}, finally{}范围,因此不会执行。

相关问题