Traverse the given directory using BFS and DFS in Java

In this post, we will see how to traverse the given directory and list out all files present in it and all its sub-directories.


 

1. Using BFS (Breadth First Search)

We can iteratively traverse the given directory and print all files present within it and its sub-directories using Breadth First Search. Below is the complete algorithm –
 

  1. Create an empty queue of File and enqueue the root directory.
     
  2. Loop till queue is not empty (all files and directories present inside the root directory are processed)
    • Pop front File from the queue.
       
    • If the popped File is a directory, get list of all files and directories present in it, add each directory to the queue and print every file.
       

Download

 

2. Using DFS (Depth First Search)

We can also recursively traverse the given directory and print all files present within it and its sub-directories using Depth First Search. We start with the root directory, get list of all files and directories present in it, recursively explore each directory and print every file.

 

Download

 
Also see:

Traverse given directory in Java 7 and Java 8

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

 
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