Java Scanner hasNextLine NoSuchElementException?

时间:2014-05-12 08:55:59

标签: java

我试图逐行读取一个大的csv文件,以便找到其中字符串的出现次数。

以下是执行此操作的代码:

public int getOffset(File file, String searched) throws FileNotFoundException {
    Scanner scanner = new Scanner(file).useDelimiter(System.getProperty("line.separator"));
    int occurences = 0;
    while (scanner.hasNextLine()) {
        String s = scanner.next();
        if (s.indexOf(searched) >= 0) {
            occurences++;
        }
    }
    return occurences;
}

但是,在读完文件的最后一行后,它会再次检查while条件,并退出此异常:

java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:838)
at java.util.Scanner.next(Scanner.java:1347)
at fr.sgcib.cva.mat.MatWriter.getOffset(MatWriter.java:83)
at fr.sgcib.cva.mat.MatWriter.writeFooter(MatWriter.java:71)
at fr.sgcib.cva.mat.NettingNodeHierarchyExtract.getLeNodes(NettingNodeHierarchyExtract.java:65)
at fr.sgcib.cva.mat.Mat.main(Mat.java:55)

为什么它没有检测到它是文件的结尾?

2 个答案:

答案 0 :(得分:4)

使用String s = scanner.nextLine();代替String s = scanner.next();

这意味着您的代码将如下所示:

public int getOffset(File file, String searched) throws FileNotFoundException {
    Scanner scanner = new Scanner(file).useDelimiter(System.getProperty("line.separator"));
    int occurences = 0;
    while (scanner.hasNextLine()) {
        String s = scanner.nextLine();
        if (s.indexOf(searched) >= 0) {
            occurences++;
        }
    }
    return occurences;
}

一般情况下,使用Scanner时,您的has...条件需要与next...数据检索方法匹配

答案 1 :(得分:4)

您正在检查下一行是否存在并扫描下一个单词。将条件更改为while(scanner.hasNext())或扫描行更改为String s = scanner.nextLine()

试试这个:

public int getOffset(File file, String searched) throws FileNotFoundException {
    Scanner scanner = new Scanner(file).useDelimiter(System.getProperty("line.separator"));
    int occurences = 0;
    while (scanner.hasNext()) {
        String s = scanner.next();
        if (s.indexOf(searched) >= 0) {
            occurences++;
        }
    }
    return occurences;
}

public int getOffset(File file, String searched) throws FileNotFoundException {
    Scanner scanner = new Scanner(file).useDelimiter(System.getProperty("line.separator"));
    int occurences = 0;
    while (scanner.hasNextLine()) {
        String s = scanner.nextLine();
        if (s.indexOf(searched) >= 0) {
            occurences++;
        }
    }
    return occurences;
}