Chapter 13. New I/O API (NIO.2)

NIO.2 was introduced with JDK 7 to provide enhanced file I/O support and access to the default filesystem. NIO.2 is supported by the java.nio.file and java.nio.file.attribute packages. The NIO.2 API is also known as “JSR 203: More New I/O APIs for the Java Platform.” Popular interfaces that are used from the API are Path, PathMatcher, FileVisitor, and WatchService. Popular classes that are used from the API are Paths and Files.

The Path Interface

The Path interface can be used to operate on file and directory paths. This class is an upgraded version of the java.io.File class. The following code demonstrates the use of some of the methods of the Path interface and the Paths class for acquiring information:

Path p = Paths.get("\\opt\\jpgTools\\README.txt");
System.out.println(p.getParent()); // \opt\jpgTools
System.out.println(p.getRoot()); // \
System.out.println(p.getNameCount()); // 3
System.out.println(p.getName(0)); // opt
System.out.println(p.getName(1)); // jpgTools
System.out.println(p.getFileName()); // README.txt
System.out.println(p.toString()); // The full path

The Path class also provides additional features, some of which are detailed in Table 13-1.

Table 13-1. Path interface capabilities
Path methodCapability

path.toUri()

Converts a path to a URI object

path.resolve(Path)

Combines two paths together

path.relativize(Path)

Constructs a path from one location to another

path.compareTo(Path)

Compares two paths against each other

The Files Class

The Files ...

Get Java 8 Pocket Guide now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.