Java Reference
In-Depth Information
How It Works
Before NIO.2, trying to traverse a directory tree involved recursion, and depending on
the implementation, it could be very brittle. The calls to get files within a folder were
synchronous and required the scanning of the whole directory before returning; gener-
ating what would appear to be an unresponsive method call to an application user. With
the new NIO.2, one can specify which folder to start traversing on, and the NIO.2 calls
will handle the recursion details. The only item that you provide to the NIO.2 API is a
class that tells it what to do when a file/folder is found (
SimpleFileVisitor
im-
plementation). NIO.2 uses a
Visitor
pattern, so it isn't required to prescan the entire
folder, but instead processes files as they are being iterated over.
The implementation of the
SimpleFileVisitor
class as an anonymous inner
class includes overriding the
visitFile(Path file, BasicFileAttrib-
utesattrs()
method. When you override this method, you can specify the tasks to
perform when a file is encountered.
The
visitFile
method returns a
FileVisitReturn
enum. This enum then
tells the
FileVisitor
which action to take:
•
CONTINUE
: Continues with the traversing of the directory tree.
•
TERMINATE
: Stops the traversing.
•
SKIP_SUBTREE
: Stops going deeper from the current tree level (use-
ful only if this enum is returned on the
preVisitDirectory()
method).
•
SKIP_SIBLINGS
: Skips the other directories at the same tree level as
the current.
The
SimpleFileVisitor
class, aside from the
visitFile()
method, also
contains the following:
•
preVisitDirectory
: Called before entering a directory to be tra-
versed.
•
postVisitDirectory
: Called after finished traversing a directory.
•
visitFile
: Called as it visits the file, as in the example code.
•
visitFileFailed
: Called if the file cannot be visited; for example,
on an I/O error.