This post will discuss how to traverse a directory, and list all files present in it and all its subdirectories in Java 7 and 8.

In the previous post, we have seen how to traverse the given directory, and print all files present in it and its subdirectories using BFS and DFS. This post will discuss the latest API introduced in Java 7 and Java 8 for this purpose.

1. Using Java 8

In Java 8, we can use the Files.walk(…) method that takes the starting file as a parameter and return a Stream of Path objects by walking the file tree in a depth-first manner, which is rooted at a given starting file.

Download Code

 
We can use the try-with-resources construct to ensure that the stream is closed after the stream operations are completed. The following example uses the Files.walk(…) method with try-with-resources.

Download Code

 
We can also use the Files.find(…) method that walks the file tree exactly the manner specified by the walk method.

Download Code

2. Using Java 7

In Java 7, we can use Files.walkFileTree(…) that walks a file tree. It requires only a starting point and an instance of FileVisitor to invoke for each file.

Download Code

That’s all about traversing a directory and listing all files in Java.

 
Also see:

List all files in a directory in Java using Guava and Apache Commons IO

 
Reference: https://docs.oracle.com/javase/8/docs/api/java/nio/file/Files.html