Scanner.hasNext() returns false
Solution 1
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")));
Solution 2
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");
Solution 3
This also happened to me today. I'm reading a plain text file from a Linux system written by some application in a Windows box and Scanner.hasNextLine()
is always false even tough there are lines with the Windows line separator and all. As said by Hound Dog, by using
Scanner scanner = new Scanner(new BufferedReader(new FileReader(file)));
it worked like a charm. FileReader or BufferedReader seem to properly identify and use some file characteristics.
Solution 4
Checking the scanner's exception may show that the file can't be read.
...
System.out.println(in.hasNext()); // return false;
IOException ex = in.ioException();
if (ex != null)
ex.printStackTrace(System.out);
...
Daniel Cisek
Updated on June 04, 2022Comments
-
Daniel Cisek almost 2 years
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 thatBufferedReader
works andScanner
didn't. -
Achow almost 10 yearsThis did the trick, though I am not sure why,my file was pretty huge, 19MB containing data(not whitespace), and it abruptly cut off when I was just using the scanner