How do I iterate through the files in a directory and its sub-directories in Java?
Files.walk
in Java succinctly traverses directories. Try this:
This piece of code streams every path, printing each file and directory recursively starting from "dir"
.
Navigating through symbolic Links with Files.walk
Using Files.walk
, keep in mind circular symbolic links could result in infinite recursion. To limit this, sparingly use FileVisitOption.FOLLOW_LINKS
and enforce a maxDepth:
Custom directory traversal with Files.walkFileTree
For maximum control and flexibility, pair FileVisitor
with Files.walkFileTree
for additional behavior:
This code opens the door for robust traversal logic within hooks for each file visit.
Utilizing Apache Commons IO
For a higher level of abstraction, turn to Apache Commons IO and its FileUtils.listFiles
:
The Apache Commons IO library delivers clean, reliable directory traversal, while ensuring your hands stay clean from boilerplate code.
Sifting through files with Files.newDirectoryStream
With Java 7+ and Files.newDirectoryStream
, you can join file filtering with directory iteration:
This approach not only efficiently uses the DirectoryStream
, but also neatly filters files by type.
Tackling exceptions in DirectoryStream
Unruly DirectoryIteratorExceptions
may pop up during your stream operations. Keep calm and handle it:
By neatly wrapping this exception, we maintain clear, good practice error management.
Choosing Path over File
In Java 8, it's recommended to forgo File
in favor of Path
when traversing directories:
This modernizes your code and aligns it with Java's recommended practices for I/O operations.
Collecting your results
During iteration, you might want to gather all paths:
With a List<Path>
, you can venture further and perform additional operations, like sorting or further filtering.
Was this article helpful?