Java Reference
In-Depth Information
file, e);
return CONTINUE;
}
// Indent for entries
private StringBuilder indent = new StringBuilder(" ");
}
Directory "FileTreeWalking"
Our ListFiles class extends the SimpleFileVisitor<Path> class and implements all the methods in
the FileVisitor<Path> interface. The SimpleFileVisitor<Path> class provides default implementa-
tions of all the methods declared in the FileVisitor<Path> interface so you can implement a subset if
you want.
The class contains the indent member of type StringBuilder — working with StringBuilder objects
is faster than using StringBuffer objects. The indent member provides indentation of the output and
is increased by two spaces each time a new directory is visited, which is indicated by the preVisitDir-
ectory() being called. When the postVisitDirectory() method is called, visiting the entries in a dir-
ectory is complete so indent is shortened by removing the last two characters.
The visitFile() method is called for each file or symbolic link in a directory that is visited. This meth-
od just outputs the entry name indented by indent . If the attributes for a file cannot be obtained, the
visitFileFailed() method is called, and here you record the problem and continue with the rest of the
tree.
Note how the constants in the FileVisitResult enumeration are imported using the static import state-
ment. This allows the constants to be used without qualifying them with the name of the enum type.
Here's the code for the application class that uses the ListFiles class:
import static java.nio.file.FileVisitOption.*;
import java.nio.file.*;
import java.io.IOException;
import java.util.EnumSet;
public class FileTreeWalking {
public static void main(String[] args) {
Path treeBase = Paths.get(
System.getProperty("java.home")).getParent().resolve("sample");
FileVisitor<Path> listFiles = new ListFiles();
int depth = 3;
try {
Files.walkFileTree(treeBase, EnumSet.of(FOLLOW_LINKS), depth,
listFiles);
Search WWH ::




Custom Search