Chapter 7. File I/O

The nonblocking (or “new”) input/output package, referred to as NIO, was added in J2SE 1.4.1 The NIO.2 extension, added in Java 7, brought in new classes for manipulating files and directories. The additions included the java.nio.file package, which is the subject of this chapter. Several of the new classes in that package, like java.nio.files.File, have been enhanced in Java 8 with methods that use streams.

Unfortunately, here is where the stream metaphor from functional programming conflicts with the same term from input/output, leading to potential confusion. For example, the java.nio.file.DirectoryStream interface has nothing to do with functional streams. It is implemented by classes that iterate over a directory tree using the traditional for-each construct.2

This chapter focuses on capabilities in I/O that support functional streams. In Java 8, several methods were added to the java.nio.file.Files class to support functional streams. Those methods are shown in Table 7-1. Note that all the methods in the Files class are static.

Table 7-1. Methods in java.nio.files.Files that return streams
Method Return type









The recipes in this chapter deal with each of these methods.

7.1 Process Files


You want to process the contents of a text file using streams.


Use the static lines method in either or java.nio​.file.Files to return ...

Get Modern Java Recipes now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.