Java Reference
In-Depth Information
You need to use the following steps to traverse a file tree:
Create a file visitor class by implementing the
java.nio.file.FileVisitor interface.
To start visiting the file tree, use the
walkFileTree() method of the Files class by specifying
the start directory and a file visitor object of the class created in the previous step. One of
the methods of the FileVisitor interface is called when a file/directory is visited or a file/
directory visit fails.
the NIO.2 apI provides the SimpleFileVisitor class, which is a basic implementation of the FileVisitor
interface. the methods in the SimpleFileVisitor class do not do anything when a file/directory is visited. when a failure
occurs, it rethrows the original exception. You can inherit your file visitor class from the SimpleFileVisitor class and
override only the methods that fit your needs.
Tip
Table 10-2 lists the methods of the FileVisitor interface with their descriptions. All methods throw an
IOException and they all return an enum constant of FileVisitResult type. Table 10-3 lists the constants defined by
the FileVisitResult enum type with their descriptions.
Table 10-2. Methods of the FileVisitor Interface
Method
Description
FileVisitResult preVisitDirectory(T dir,
BasicFileAttributes attrs) throws IOException
This method is called once before visiting entries in a
directory.
FileVisitResult postVisitDirectory(T dir,
IOException exc) throws IOException
This method is called after entries in a directory (and all
of their descendants) have been visited. It is invoked even
if there are errors during the visit of entries in a directory.
If there was any exception thrown during the iteration of
a directory, the exception object is passed to this method
as the second argument. If the second argument to
this method is null , there was no exception during the
directory iteration.
FileVisitResult visitFile(T file,
BasicFileAttributes attrs) throws IOException
This method is called when a file in a directory is visited.
FileVisitResult visitFileFailed(T file,
IOException exc) throws IOException
This method is called when a file or directory could not
be visited for any reason.
Table 10-3. Enum Constants of FileVisitResult and Their Descriptions
Enum Constant
Description
CONTINUE
Continues processing
SKIP_SIBLINGS
Continues processing without visiting the siblings of the file or directory. If it is returned from
the preVisitDirectory() method, the entries in the current directory is also skipped and the
postVisitDirectory() method is not called on that directory.
SKIP_SUBTREE
Continues processing without visiting entries in the directory. It is meaningful only when
returned from the preVisitDirectory() method. Otherwise, its effect is the same as CONTINUE .
TERMINATE
Terminates the file visiting process.
 
Search WWH ::




Custom Search