I have faced a problem to count line number using lines() method of BufferedReader
. Following is the content of test.txt
file.
1 Career
2 Filmography
3 Awards
4 References
5 External
Here is the source code to count line number twice.
BufferedReader br=new BufferedReader(new FileReader(new File("test.txt")));
long lineNo=br.lines().count();
long lineNo2=br.lines().count();
System.out.println(lineNo); // 5
System.out.println(lineNo2);// 0
Here, I have question why second line of lineNo2
print 0
instead of 5
? Thanks in advance.
From the Javadoc:
count()
is a terminal operation. Thus the position of the reader is unspecified after the firstcount()
-call.The java 8 API specifies here that
So after you execute the
br.lines().count()
statement there is no guarantee on the pointer's location.The
lines().count()
invocation consumes the data from the file and when invoked again without closing the stream. It cannot consume the same data again by invokingbr.lines().count()
.The
BufferedReader.lines()
method returns a stream. Accessing the stream (eg when you perform acount()
on it), will read lines from the buffer, moving the current position in theBufferedReader
forward.When you do a
count()
, the entire stream is read, so theBufferedReader()
will - probably - be at the end. A second invocation oflines()
will return a stream that will read no lines, because the reader is already at the end of its data.The javadoc of
BufferedReader.lines()
specifies:I read this to mean that there is no guarantee that it is immediately after the last line returned from the stream, but as a count consumes all lines, I am pretty sure it is at the end. Going back to the beginning of a reader is (usually) not possible.
If you need to do multiple actions with the data from the
BufferedReader.lines()
you either need to process to stream once, or you need to collect the data into temporary storage. But note that executing a terminal operation like a count of lines (or a collect) might never complete (eg if theBufferedReader
is fed from an infinite source).