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

Viewed 112

Originally, I declared my Scanner as

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

I had it read a CSV file of ~3000 lines, and it gave me a "no such element" error when it reached the 362nd line. The error went away after I changed the declaration to

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

but why did this make a difference?

Here's lines 360-362 of my CSV file (the "no such element" error occurred after reading 31 on line 362):

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

And here's my code:

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

Thank you!

0 Answers
Related