2

When using the method

java.nio.file.Files.walkFileTree(Path root, Set options, int maxDepth, FileVisitor visitor)

one can specify the maximum depth of files to visit. Is there also a way to specify that only paths of a specific, exact depth shall be visited?

More specifically, I only want to visit directories, but this could be easily checked with

if (attrs.isDirectory()) {
    // do something
}

in the visitFile callback.


Example: Assume I have a directory structure with the files root/dir1/dir11/file.a and root/dir2/file.b and I call walkFileTree on root with maxDepth=2. Then, I only want to process

root/dir1/dir11

I neither want to process the file root/dir2/file.b, which has also a depth of two, nor the other directory paths with a depth less than two:

root
root/dir1
root/dir2
oberlies
  • 10,674
  • 2
  • 54
  • 98

1 Answers1

3

Interestingly, the naive implementation does exactly what I want:

Files.walkFileTree(root, EnumSet.noneOf(FileVisitOption.class), 2, new SimpleFileVisitor<Path>() {
    @Override
    public FileVisitResult visitFile(Path path, BasicFileAttributes attrs) throws IOException {
        if (attrs.isDirectory()) {
            process(path);
        }
        return FileVisitResult.CONTINUE;
    }
});

That is, for the given example, it will exactly only process root/dir1/dir11.

The solution makes use of the apparently contradictory approach to filter for directories in visitFiles. However the JavaDoc of walkFileTree explains why this results in the desired behaviour:

For each file encountered this method attempts to read its java.nio.file.attribute.BasicFileAttributes. If the file is not a directory then the visitFile method is invoked with the file attributes. (...)

The maxDepth parameter is the maximum number of levels of directories to visit. (...) The visitFile method is invoked for all files, including directories, encountered at maxDepth (...)

oberlies
  • 10,674
  • 2
  • 54
  • 98