Curly quotes causing Java Scanner hasNextLine() to be false — why?

前端 未结 3 1829
遥遥无期
遥遥无期 2021-01-17 12:22

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

3条回答
  •  既然无缘
    2021-01-17 12:45

    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.

提交回复
热议问题