Java 8 BufferedReader lines() method prints different count number

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).


From the Javadoc:

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.

count() is a terminal operation. Thus the position of the reader is unspecified after the first count()-call.


The java 8 API specifies here that

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.

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 invoking br.lines().count().