如何通过 CRLF 逐行读取文件

How to read file line by line by CRLF

我有以下文件:

和以下代码:

Scanner scanner = new Scanner(new FileReader(new File(file.txt)));
scanner.useDelimiter("\r\n");
int i = 0;
while (scanner.hasNext()) {
    scanner.nextLine();
    i++;
}
System.out.println(i);

它returns 5.

预期结果:2.

我做错了什么?

我只想按 CRLF 拆分(不是 LF)。

使用scanner.next()调用指定的分隔符。

scanner.nextLine() 将使用 \n(确切模式为 \r\n|[\n\r\u2028\u2029\u0085])作为分隔符,因此长度为 5。

while (scanner.hasNext()) {
    scanner.next();
    i++;
}