Open In App

Traversing directory in Java using BFS

Last Updated : 19 Jan, 2024
Improve
Improve
Like Article
Like
Save
Share
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)
 



Previous Article
Next Article

Similar Reads

Maximum points by traversing from top left of Matrix to bottom right by two persons
Given a matrix grid[][] of order N*M with numbers 0-9 in the cells. The task is to find the maximum amount of money collected when two persons move from (0, 0) to (N-1, M-1) by moving only right and down. If both persons are at the same cell, then only one of them can pick the money at that location. Examples: Input: 1 1 1 1 0 1 1 1 1Output: 8Expla
7 min read
Traversing a Map and unordered_map in C++ STL
The maps are described as mapped associative containers for elements where each element has a key and value assigned to it. Another form of map container seen in the C++ STL is the unordered map. It is the same as map containers just that they don't store the data in sorted order. We can traverse map and unordered_map using 4 different ways which a
6 min read
Water Jug problem using BFS
You are given an m liter jug and a n liter jug. Both the jugs are initially empty. The jugs don’t have markings to allow measuring smaller quantities. You have to use the jugs to measure d liters of water where d is less than n. (X, Y) corresponds to a state where X refers to the amount of water in Jug1 and Y refers to the amount of water in Jug2 D
15+ min read
Diameter of n-ary tree using BFS
N-ary tree refers to the rooted tree in which each node having atmost k child nodes. The diameter of n-ary tree is the longest path between two leaf nodes. Various approaches have already been discussed to compute diameter of tree. Diameter of an N-ary tree Diameter of a Binary Tree in O(n) Diameter of a Binary Tree Diameter of a tree using DFS Thi
7 min read
Count the number of nodes at given level in a tree using BFS.
Given a tree represented as an undirected graph. Count the number of nodes at a given level l. It may be assumed that vertex 0 is the root of the tree. Examples: Input : 7 0 1 0 2 1 3 1 4 1 5 2 6 2 Output : 4 Input : 6 0 1 0 2 1 3 2 4 2 5 2 Output : 3 BFS is a traversing algorithm that starts traversing from a selected node (source or starting node
9 min read
BFS using vectors &amp; queue as per the algorithm of CLRS
Breadth-first search traversal of a graph using the algorithm given in CLRS book. BFS is one of the ways to traverse a graph. It is named so because it expands the frontier between discovered and undiscovered vertices uniformly across the breadth of the frontier. What it means is that the algorithm first discovers all the vertices connected to "u"
11 min read
Finding the path from one vertex to rest using BFS
Given an adjacency list representation of a directed graph, the task is to find the path from source to every other node in the graph using BFS. Examples: Input: Output: 0 &lt;- 2 1 &lt;- 0 &lt;- 2 2 3 &lt;- 1 &lt;- 0 &lt;- 2 4 &lt;- 5 &lt;- 2 5 &lt;- 2 6 &lt;- 2 Approach: In the images shown below: que[] array stores the vertices reached and we wi
14 min read
Implementation of BFS using adjacency matrix
Breadth First Search (BFS) has been discussed in this article which uses adjacency list for the graph representation. In this article, adjacency matrix will be used to represent the graph. Adjacency matrix representation: In adjacency matrix representation of a graph, the matrix mat[][] of size n*n (where n is the number of vertices) will represent
7 min read
Program to print all the non-reachable nodes | Using BFS
Given an undirected graph and a set of vertices, we have to print all the non-reachable nodes from the given head node using a breadth-first search. For example: Consider below undirected graph with two disconnected components: In this graph, if we consider 0 as a head node, then the node 0, 1 and 2 are reachable. We mark all the reachable nodes as
8 min read
Find integral points with minimum distance from given set of integers using BFS
Given an integer array A[] of length N and an integer K. The task is to find K distinct integral points that are not present in the given array such that the sum of their distances from the nearest point in A[] is minimized. An integral point is defined as the point with both the coordinates as integers. Also, in the x-axis, we don't need to consid
9 min read
Practice Tags :