为什么 Java Scanner 会抛出 NoSuchElementException,除非我通过路径而不是 File 声明我的 Scanner?

Why does Java Scanner throw a NoSuchElementException unless I declare my Scanner by Path instead of File?

提问人:jruan 提问时间:2/8/2021 更新时间:2/8/2021 访问量:118

问:

最初,我将我的扫描仪声明为

Scanner in = new Scanner(new File(filename));

我让它读取了一个 ~3000 行的 CSV 文件,当它到达第 362 行时,它给了我一个“没有这样的元素”错误。将声明更改为

Scanner in = new Scanner(Paths.get(filename));

但为什么会有所作为呢?

这是我的 CSV 文件的第 360-362 行(在第 362 行阅读后发生“没有此类元素”错误):31

4,"T Sanchez, A Polyakov, JP Richard, D Efimov",1,29,0,0,0
3,"T Sánchez, JA Moreno, JA Peralta",4,30,0,0,0
3,"FAO Ricardez, T Sánchez, JA Moreno",5,31,0,0,0

这是我的代码:

String filename = "before.csv";
Scanner in = new Scanner(new File(filename)); // changed to Paths.get(filename)
PrintStream out = new PrintStream(new File("after.csv"));
        
out.println(in.nextLine());

String DELIMITER = ",";
in.useDelimiter(DELIMITER);

while(in.hasNext()) {
    int author_count = in.nextInt();
    out.print(author_count + ",");
    
    for(int i = 0; i < author_count; i++) {
        String cur_author = in.next();
        ...
    }
            
    out.print("<bitmask>" + ",");
    
    for(int i = 0; i < 4; i++) {
        int a = in.nextInt(); // where the error occurred
        out.print(a + ",");
    }
    out.println(in.nextLine().replace(",", ""));
}
        
in.close();
out.close();

谢谢!

java.util.scanner

评论

0赞 samabcde 2/8/2021
1. 请同时提供您正在使用的 jdk 版本和 .2.查看文件是否仅包含1-362行,从而产生相同的错误。如果是这样,请在帖子中添加 1-362 行。仅 360-362 行无法重现该错误。3.在第362行记录错误之前的内容也很有用。System.out.println(Charset.defaultCharset());in.nextInt()

答: 暂无答案