Traverse a Directory and List all the Files in Java 7 and Java 8

In this post, we will see how to traverse a directory and list out 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. In this post, we will discuss latest API introduced in Java 7 and Java 8 for this purpose.

 

1. Java 8

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

Download

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

Download

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

Download

 

2. 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

 
Also see: List all files in a directory in Java using Guava and Apache Commons

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

 
Thanks for reading.




Please use ideone or C++ Shell or any other online compiler link to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂
 





Leave a Reply

Notify of
avatar
wpDiscuz