Skip to content
Related Articles

Related Articles

Traversing directory in Java using BFS

View Discussion
Improve Article
Save Article
  • Last Updated : 24 Mar, 2018
View Discussion
Improve Article
Save Article

Given a directory, print all files and folders present in directory tree rooted with given directory.

We can iteratively traverse directory in BFS using below steps. We create an empty queue and we first enqueue given directory path. We run a loop while queue is not empty. We dequeue an item from queue. If the popped item is a directory, get list of all files and directories present in it, add each directory to the queue. If the popped item is a file, we print its name.

// Java program to print all files/directories
// present in a directory.
import java.util.LinkedList;
import java.util.Queue;
class FileUtils {
    public static void printDirsFiles(String inputDir)
        /* make a queue to store files and directories */
        Queue<File> queue = new LinkedList<>();
        queue.add(new File(inputDir));
        /* loop until queue is empty -*/
        while (!queue.isEmpty()) {
            /* get next file/directory from the queue */
            File current = queue.poll();
            File[] fileDirList = current.listFiles();
            if (fileDirList != null) {
                /* Enqueue all directories and print 
                   all files. */
                for (File fd : fileDirList) {
                    if (fd.isDirectory()) 
    /* Iterative function to traverse given 
       directory in Java using BFS*/
    public static void main(String[] args)
        String inputDir = "C:\\Programs";

This article is contributed by Pranav. If you like GeeksforGeeks and would like to contribute, you can also write an article using or mail your article to See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!