I\'ve been having an issue getting the java.util.Scanner to read a text file I saved in Notepad, even though it works fine with others. Basically, when it tries to read the
Scanner
's hasNextLine
method will just return false if it encountered encoding error in the input file. Without any exception. This is frustrating, and it is not documented anywhere, even in JDK 8 documentation.
If you just want to read a file line-by-line, use this instead:
final BufferedReader input = new BufferedReader(new InputStreamReader(new FileInputStream("inputfile.txt"), "inputencoding"));
while (true) {
String line = input.readLine();
if (line == null) break;
// process line
}
input.close();
Make sure the inputencoding
above is replaced with the correct encoding of the file. Most likely it is utf-8
or ascii
. Even if the encoding mismatches, it won't prematurely terminate like Scanner
.