I have the following file:
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++; }