Traversing directory in Java using BFS
Last Updated :
19 Jan, 2024
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
import java.io.File;
import java.util.LinkedList;
import java.util.Queue;
class FileUtils {
public static void printDirsFiles(String inputDir)
{
Queue<File> queue = new LinkedList<>();
queue.add( new File(inputDir));
while (!queue.isEmpty()) {
File current = queue.poll();
File[] fileDirList = current.listFiles();
if (fileDirList != null ) {
for (File fd : fileDirList) {
if (fd.isDirectory())
queue.add(fd);
else
System.out.println(fd);
}
}
}
}
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)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...