gstackoverflow gstackoverflow - 5 months ago 26
Java Question

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("\r\n");
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 \r\n|[\n\r\u2028\u2029\u0085]) as delimiter, hence the length is 5.

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