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:
Pathp=Paths.get("\\opt\\jpgTools\\README.txt");System.out.println(p.getParent());// \opt\jpgToolsSystem.out.println(p.getRoot());// \System.out.println(p.getNameCount());// 3System.out.println(p.getName(0));// optSystem.out.println(p.getName(1));// jpgToolsSystem.out.println(p.getFileName());// README.txtSystem.out.println(p.toString());// The full path
The Path class also provides additional features, some of which are detailed in Table 13-1.
| 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 ... |