Trivial traversal of a folder

Implementing the FileVisitor interface requires that we override its four methods. However, NIO.2 comes with a built-in simple implementation of this interface called SimpleFileVisitor. For simple cases, extending this class is more convenient than implementing FileVisitor since it allows us to override only the necessary methods.

For example, let's assume that we store our e-courses in the subfolders of the D:/learning folder, and we want to visit each of these subfolders via the FileVisitor API. If something goes wrong during the iteration of a subfolder, we will simply throw the reported exception.

In order to shape this behavior, we need to override the postVisitDirectory() method, as follows:

class PathVisitor extends SimpleFileVisitor<Path> {

@Override
public FileVisitResult postVisitDirectory(
Path dir, IOException ioe) throws IOException {

if (ioe != null) {
throw ioe;
}

System.out.println("Visited directory: " + dir);

return FileVisitResult.CONTINUE;
}
}

In order to use the PathVisitor class, we just need to set up the path and call one of the Files.walkFileTree() methods, as follows (the flavor of walkFileTree() that's used here gets the starting file/folder and the corresponding FileVisitor):

Path path = Paths.get("D:/learning");
PathVisitor visitor = new PathVisitor();

Files.walkFileTree(path, visitor);

By using the preceding code, we will receive the following output:

Visited directory: D:learningooksajax
Visited directory: D:learningooksangular
...
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset