Streams from Factory Methods in the Files Class – Streams

Streams from Factory Methods in the Files Class

A detailed discussion of the NIO2 File API that provides the classes for creating the various streams for reading files, finding files, and walking directories in the file system can be found in Chapter 21, p. 1285.

Analogous to the lines() method in the BufferedReader class, a static method with the same name is provided by the java.nio.file.Files class that creates a stream for reading the file content as lines.

In the example below, a Path is created at (1) to represent a file on the file system. A stream is created to read lines from the path at (2) in the header of the try-with-resources statement (ยง7.7, p. 407). As streams are AutoCloseable, such a stream is automatically closed after the try block completes execution. As no character set is specified, bytes from the file are decoded into characters using the UTF-8 charset. A terminal operation is initiated at (3) on this stream to count the number of lines in the file. Again, each line in the stream can be processed as desired.

Click here to view code image

Path path = Paths.get(“CD_Data.txt”);                             // (1)
try (Stream<String> lStream = Files.lines(path)) {                // (2)
  System.out.println(“Number of lines: ” + lStream.count());      // (3) 13
} catch (FileNotFoundException e) {
  e.printStackTrace();
} catch (IOException e) {
  e.printStackTrace();
}

The following static methods for building a Stream<String> from a text file are defined in the java.nio.file.Files class:

Click here to view code image

static Stream<String> lines(Path path)
static Stream<String> lines(Path path, Charset cs)

Return a finite sequential ordered Stream of String, where the elements are text lines read from a file given by the specified path. The first method decodes the bytes into characters using the UTF-8 charset. The charset to use can be explicitly specified, as in the second method.

Leave a Reply

Your email address will not be published. Required fields are marked *