This post will discuss 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. Following is the complete algorithm:

  1. Create an empty queue of File class and enqueue the root directory.
  2. Loop till queue becomes 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 the list of all files and directories present in it, add each directory to the queue and print every file.

The algorithm can be implemented as follows in Java:

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. The idea is to start with the root directory, get the list of all files and directories present in it, recursively explore each directory, and print every file.

Download

 
Also see:

Traverse a directory and list all files in Java

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