Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scanner.hasNext() returns false

I have directory with many files in it - each with over 800 lines in it. Hovewer, when I try to read it using Scanner, it seems empty.

File f1 = new File("data/cityDistances/a.txt"),
     f2 = new File("data/cityDistances/b.txt");
System.out.println(f1.exists() && f2.exists()); //return true
System.out.println(f1.getTotalSpace() > 0 && f2.getTotalSpace() > 0); //return true
Scanner in = new Scanner(f1);
System.out.println(in.hasNext()); // return false;
System.out.println(in.hasNextLine()); //return false;

Why can it behave like that?


I've managed to do it using BufferedReader. Nonetheless, it seems even more strange that BufferedReader works and Scanner didn't.

like image 769
Daniel Cisek Avatar asked Dec 01 '22 01:12

Daniel Cisek


2 Answers

As the default delimeter for Scanner is whitespace, that would imply your a.txt contains only whitespace - does it have 800 lines of whitespace? ;)

Have you tried the following?

new Scanner(new BufferedReader(new FileReader("a.txt")));
like image 162
James Bassett Avatar answered Dec 03 '22 13:12

James Bassett


I had a similar problem today reading a file with Scanner. I specified the encoding type of the file and it solved the problem.

scan = new Scanner(selectedFile,"ISO-8859-1");
like image 29
Hugues Avatar answered Dec 03 '22 14:12

Hugues