繁体   English   中英

为什么 Java 扫描仪会抛出 NoSuchElementException,除非我通过路径而不是文件声明我的扫描仪?

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

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

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();

谢谢!

区别在于代码。

public Scanner(File source) throws FileNotFoundException {
    this((ReadableByteChannel)(new FileInputStream(source).getChannel()));
}



public Scanner(Path source) throws IOException
{
    this(Files.newInputStream(source));
}

我相信第一种情况,因为它将它加载到缓冲区中,这就是它可能抛出 NoSuchElementException 的原因

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM