O'Reilly logo

Java Pocket Guide, 4th Edition by Robert Liguori, Patricia Liguori

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 method Capability

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required