"Walk the Line" in JAVA

by zemion
Posted in Java

When traversing the file tree, JAVA provides a FileVisitor as part of the features intoduced with NIO2. With this interface, a file tree can be traversed to any depth, performing actions on the files and/or directories found on any branch. A nice feature and a lot faster than previous (recursive) solutions. Thanks, NIO2!

The official tutorial by Oracle mentions two methods to traverse the file tree:

  • walkFileTree(Path, FileVisitor) as a simple method, accepting an initial path and a FileVisitor object, and
  • walkFileTree(Path, Set<FileVisitOption>, int, FileVisitor), basically doing the same, but accepting more options.

While for most use cases the first method might be sufficient, the second option provides more flexibility by offering the possibility to limit the depth or letting the FileVisitor follow symbolic links.

Now, every tutorial shows you how to use the second forur-argument method using EnumSet.of(java.nio.file.FileVisitOption.FOLLOW_LINKS) as second argument. What most of the tutorials fail to mention is how to use the same method (thus having the posibility to limit the depth of the search) while not following symbolic links.

Passing a null value leads to an NullPointerException. Creating an EnumSet of null (using EnumSet.of(null)) leads to exactly the same result. What we need is an empty EnumSet of FileVisitOption. This can be easily achieved by EnumSet.noneOf(java.nio.file.FileVisitOption.class). Now we can limit the depth without following symlinks - whenever needed.

Did you like this text? Maybe it even helped you? I certainly hope it did. If you want to show your appreciation, you can send me a tip.