Chapter 2. New I/O

 

This chapter covers

  • The new Java 7 I/O APIs (aka NIO.2)
  • Path—the new foundation for file- and directory-based I/O
  • The Files utility class and its various helper methods
  • How to solve common I/O use cases
  • An introduction to asynchronous I/O

One of the larger API changes in the Java language—a major update to the set of I/O APIs, called “more New I/O” or NIO.2 (aka JSR-203)—is the focus of this chapter. NIO.2 is a set of new classes and methods, that primarily live in the java.nio package.

  • It’s an out-and-out replacement of java.io.File for writing code that interacts with the filesystem.
  • It contains new asynchronous classes that will allow you to perform file and network I/O operations in a background thread without manually configuring thread pools and other low-level concurrency constructs.
  • It simplifies coding with sockets and channels by introducing a new NetworkChannel construct.

Let’s look at an example use case. Imagine your boss asked you to write a Java routine that went through all the directories on the production server and found all of the properties files that have been written with a variety of read/write and ownership permissions. With Java 6 (and below) this task is almost impossible for three reasons:

2.1. Java I/O—a history

2.2. Path—a foundation of file-based I/O

2.3. Dealing with directories and directory trees

2.4. Filesystem I/O with NIO.2

2.5. Asynchronous I/O operations

2.6. Tidying up Socket-Channel functionality

2.7. Summary