Streams from a BufferedReader – Streams
Streams from a BufferedReader
A BufferedReader allows contents of a text file to be read as lines. A line is a sequence of characters terminated by a line terminator sequence. Details of using a Buffered-Reader are covered in §20.3, p. 1251. A simple example of creating streams on text files using a BufferedReader is presented below.
At (1) and (2) in the header of the try-with-resources statement (§7.7, p. 407), a BufferedReader is created to read lines from a given file, and a stream of String is created at (3) by the lines() method provided by the BufferedReader class. These declarations are permissible since both the buffered reader and the stream are Auto-Closeable. Both will be automatically closed after the try block completes execution. A terminal operation is initiated at (4) on this stream to count the number of lines in the file. Of course, each line from the stream can be processed depending on the problem at hand.
try ( FileReader fReader = new FileReader(“CD_Data.txt”); // (1)
BufferedReader bReader = new BufferedReader(fReader); // (2)
Stream<String> lStream = bReader.lines() ) { // (3)
System.out.println(“Number of lines: ” + lStream.count()); // (4) 13
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
The following method for building a Stream<String> from a text file is defined in the java.io.BufferedReader class:
Stream<String> lines()
Returns a finite sequential ordered Stream of Strings, where the elements are text lines read by this BufferedReader.
The reader position in the file is not guaranteed after the stream terminal operation completes.
The result of the terminal stream operation is undefined if the reader is operated upon during the execution of this operation.
Any operation on a Stream returned by a BufferedReader that has already been closed will throw an UncheckedIOException.
Archives
- July 2024
- June 2024
- May 2024
- March 2024
- February 2024
- January 2024
- December 2023
- October 2023
- September 2023
- May 2023
- March 2023
- January 2023
- December 2022
- November 2022
- October 2022
- September 2022
- August 2022
- July 2022
- April 2022
- March 2022
- November 2021
- October 2021
- September 2021
- July 2021
- June 2021
- March 2021
- February 2021
Calendar
M | T | W | T | F | S | S |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | |||
5 | 6 | 7 | 8 | 9 | 10 | 11 |
12 | 13 | 14 | 15 | 16 | 17 | 18 |
19 | 20 | 21 | 22 | 23 | 24 | 25 |
26 | 27 | 28 | 29 | 30 |