Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Scanner unable to read file

I'm doing a very simple text-parsing program, using files given to me by a friend. However, when I open the file using a Scanner like so,

Scanner scan = new Scanner(new File(path));
System.err.println(scan.hasNext());
while(scan.hasNextLine())
    System.err.println(scan.nextLine());
System.err.println(scan.next());

result:

false
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:855)
at java.util.Scanner.next(Scanner.java:1364)
at Test.main(Test.java:18)

the scanner treats the file(which is some 1400 lines long) as empty.

Can anyone think of any reason a scanner might not be able to see a file? I suspect the fact that the file was imported from a Windows machine to a Linux machine may have something to do with it, but my mind is open to other possibilities

edited for formatting and code errors

like image 395
Zach H Avatar asked Oct 20 '25 17:10

Zach H


2 Answers

I resolved it using new Scanner(new BufferedReader(new FileReader(fileName))) instead of new Scanner(new File(fileName))

like image 135
Ajitsen Avatar answered Oct 23 '25 05:10

Ajitsen


Found the problem: Looked at the file byte by byte. found an EOF character in the first byte. Java was ignoring the rest of the file.

like image 39
Zach H Avatar answered Oct 23 '25 06:10

Zach H



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!