- A cleaner exception handling.
- Full access to the file system with new features (support of specific operating system attributes, •
- symbolic links, etc.).
- The addition of the notion of FileSystemand FileStore(e.g., a partition disk).
- Utility methods (move/copy files, read/write binary or text files, path, directories, etc.).
The following code shows you the new java.nio.file.Pathinterface (used to locate a file or a directory in a file system) as well as the utility class java.nio.file.Files(used to get information about the file or to manipulate it). From Java SE 7 onward it is recommended to use the new NIO.2 even if the old java.io package has not been deprecated.
The following code, gets some information about the source.txt file, copies it to the dest.txt file, displays its content, and deletes it.
Path path = Paths.get("source.txt"); boolean exists = Files.exists(path); boolean isDirectory = Files.isDirectory(path); boolean isExecutable = Files.isExecutable(path); boolean isHidden = Files.isHidden(path); boolean isReadable = Files.isReadable(path); boolean isRegularFile = Files.isRegularFile(path); boolean isWritable = Files.isWritable(path); long size = Files.size(path); // Copies a file Files.copy(Paths.get("source.txt"), Paths.get("dest.txt")); // Reads a text file List<String> lines = Files.readAllLines(Paths.get("source.txt"), UTF_8); for (String line : lines) { System.out.println(line); } // Deletes a file Files.delete(path);