Java 8 BufferedReader lines() method prints different count number

被刻印的时光 ゝ 提交于 2020-01-03 08:28:12

问题


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.


回答1:


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




回答2:


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.




回答3:


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



来源:https://stackoverflow.com/questions/23564103/java-8-bufferedreader-lines-method-prints-different-count-number

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!