How to read file line by line by CRLF

I have the following file:

enter image description here

and following code:

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

It returns 5.

expected result: 2.

What do I wrong?

I want to split by CRLF only (not LF).

Answer

Use scanner.next() to invoke the delimiter specified.

scanner.nextLine() will use n (exact pattern is rn|[nru2028u2029u0085]) as delimiter, hence the length is 5.

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

Leave a Reply

Your email address will not be published. Required fields are marked *