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.
Leave a Reply