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.
| Method | Return type |
|---|---|
|
|
|
|
|
|
|
|
The recipes in this chapter deal with each of these methods.
7.1 Process Files
Problem
You want to process the contents of a text file using streams.
Solution
Use the static lines method in either java.io.BufferedReader or java.nio.file.Files to return ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access