riedquat - valueable resource for those who seek.
Home Blog Technical Reports Art Articles RapiDocs Coding Bugs Links Reviews Projects: CherBot Daimonin Gridarta

JDK7 usage: walkFileTree example

previous: JDK7 Review - java.util
next: JDK7 usage: WatchService example
twitter button

I've just played around with JDK7 method Files.walkFileTree().

Here's my simple use case: I want to list all directory contents in a directory. The directory possibly is a Subversion sandbox. Therefore I want to ignore all directories named ".svn" and their contents.

As the example shows, this is now possible without doing the depth recursion myself. The method Files.walkFileTree() will now do that for me.

There is a minor caveat for those who don't read the documentation precisely enough. The method visitFile() is not invoked for directories. For directories, method preVisitDirectory() is invoked.

 1 import java.io.IOException;
 2 import java.nio.file.FileVisitResult;
 3 import java.nio.file.FileVisitor;
 4 import java.nio.file.Files;
 5 import java.nio.file.Path;
 6 import java.nio.file.Paths;
 7 import java.nio.file.SimpleFileVisitor;
 8 import java.nio.file.attribute.BasicFileAttributes;
 9 
10 /** Lists all files in the given directory recursively.
11  * .svn directories are ignored.
12  * @author <a href="mailto:cher@riedquat.de">Christian Hujer</a>
13  */
14 public class Find extends SimpleFileVisitor<Path> {
15 
16     /** Main program.
17      * @param args Command line arguments - directories to search.
18      */
19     public static void main(final String... args) throws IOException {
20         final FileVisitor<Path> fileVisitor = new Find();
21         for (final String arg : args.length > 0 ? args : new String[] {"."}) {
22             final Path root = Paths.get(arg);
23             Files.walkFileTree(root, fileVisitor);
24         }
25     }
26 
27     /** {@inheritDoc} */
28     public FileVisitResult preVisitDirectory(final Path dir, final BasicFileAttributes attrs) {
29         if (".svn".equals(dir.getFileName().toString())) {
30             return FileVisitResult.SKIP_SUBTREE;
31         }
32         System.out.println(dir);
33         return FileVisitResult.CONTINUE;
34     }
35 
36     /** {@inheritDoc} */
37     public FileVisitResult visitFile(final Path file, final BasicFileAttributes attrs) {
38         System.out.println(file);
39         return FileVisitResult.CONTINUE;
40     }
41 
42 }

Download Find.java.

End Of Line
 . 
..: