The Wayback Machine - https://web.archive.org/web/20240120163403/https://www.geeksforgeeks.org/traversing-directory-java-using-bfs/
Open In App
Related Articles

Traversing directory in Java using BFS

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Report issue
Report

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




// Java program to print all files/directories
// present in a directory.
import java.io.File;
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())
                        queue.add(fd);
                    else
                        System.out.println(fd);
                }
            }
        }
    }
  
    /* Iterative function to traverse given
    directory in Java using BFS*/
    public static void main(String[] args)
    {
        String inputDir = "C:\\Programs";
        printDirsFiles(inputDir);
    }
}


Time Complexity: O(n), where n is the number of files and folders present in directory tree rooted with given directory
Auxiliary Space: O(n)
 


Feeling lost in the vast world of Backend Development? It's time for a change! Join our Java Backend Development - Live Course and embark on an exciting journey to master backend development efficiently and on schedule.
What We Offer:
  • Comprehensive Course
  • Expert Guidance for Efficient Learning
  • Hands-on Experience with Real-world Projects
  • Proven Track Record with 100,000+ Successful Geeks

Commit to GfG's Three-90 Challenge! Purchase a course, complete 90% in 90 days, and save 90% cost click here to explore.
Last Updated : 19 Jan, 2024
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads
Complete Tutorials