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.
The BufferedReader.lines()
method returns a stream. Accessing the stream (eg when you perform a count()
on it), will read lines from the buffer, moving the current position in the BufferedReader
forward.
When you do a count()
, the entire stream is read, so the BufferedReader()
will - probably - be at the end. A second invocation of lines()
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:
After execution of the terminal stream operation there are no guarantees that the reader will be at a specific position from which to read the next character or line.
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 the BufferedReader
is fed from an infinite source).