134. Walking paths

There are different solutions for walking (or visiting) paths, and one of them is provided by the NIO.2 API via the FileVisitor interface.

This interface exposes a set of methods that represent checkpoints in the recursive process of visiting the given path. By overriding these checkpoints, we are allowed to interfere in this process. We can process the currently visited file/folder and decide what should happen further via the FileVisitResult enumeration, which contains the following constants:

  • CONTINUE: The traversal process should continue (visit next file, folder, skip a failure, and so on)
  • SKIP_SIBLINGS: The traversal process should continue without visiting the siblings of the current file/folder
  • SKIP_SUBTREE: The traversal process should continue without visiting the entries in the current folder
  • TERMINATE: The traversal should brutally terminate

The methods that are exposed by FileVisitor are as follows:

  • FileVisitResult visitFile​(T file, BasicFileAttributes attrs) throws IOException: Automatically called for each visited file/folder
  • FileVisitResult preVisitDirectory​(T dir, BasicFileAttributes attrs) throws IOException: Automatically called for a folder before visiting its content
  • FileVisitResult postVisitDirectory​(T dir, IOException exc) throws IOException: Automatically called after the content in the directory (including descendants) is visited or, during the iteration of the folder, an I/O error occurred or the visit was programmatically aborted
  • FileVisitResult visitFileFailed​(T file, IOException exc) throws IOException: Automatically called when the file cannot be visited (accessed) for different reasons (for example, the file's attributes cannot be read or a folder cannot be opened)

Ok; so far, so good! Let's continue with several practical examples.

..................Content has been hidden....................

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