Open In App

List all Files from a Directory Recursively in Java

Last Updated : 03 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In Java, when working with file systems, sometimes it is necessary to list all files from a directory, including those within its subdirectories. This process, known as recursive directory traversal, allows us to explore the entire hierarchy of files and folders starting from a given directory. Java provides classes like File and Path to handle file system operations, and recursion simplifies the process of listing files recursively.

In this article, we will explore how to list all files from a directory recursively.

List all Files from a Directory Recursively

Java offers multiple options for this, each with its advantages and considerations:

1. Using the File Class:

  • Create a File object representing the root directory.
  • Utilize the listFiles() method on the File object.
  • Implement recursion: For each directory in the retrieved array, call the listFiles() method again recursively, passing the directory as the new root. This iteratively explores nested subdirectories and adds their files to the overall list.

2. Using the Files Class (Java NIO.2):

  • Import the java.nio.file package.
  • Utilize the Files.newDirectoryStream(Path start, PathFilter… filters) method. This creates a stream of Path objects for all files and directories within the specified path, considering any optional filters provided.
  • Iterate through the stream: Each element in the stream represents a file or directory within the target path. Extract the paths and add them to your list.
  • For directories, repeat step 2 recursively. Use the directory path as the new starting point for exploring its subdirectories and their files.

Java program to List Files from a Directory using the Files class to list all files recursively:

Java




// Java Program to list all files
// From a directory recursively
import java.io.IOException;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
  
public class ListFilesRecursively 
{
    public static void main(String[] args) throws IOException 
    {
        Path rootPath = Paths.get("D:", "root");
  
        List<Path> allFiles = new ArrayList<>();
        listAllFiles(rootPath, allFiles);
  
        System.out.println("Found files:");
        allFiles.forEach(System.out::println);
    }
  
    private static void listAllFiles(Path currentPath, List<Path> allFiles)
      throws IOException 
    {
        try (DirectoryStream<Path> stream = Files.newDirectoryStream(currentPath)) 
        {
            for (Path entry : stream) {
                if (Files.isDirectory(entry)) {
                    listAllFiles(entry, allFiles);
                } else {
                    allFiles.add(entry);
                }
            }
        }
    }
}


Output:

Below in the output image, we can see all the files are listed.

Output in Console

Explanation of the above Program:

  • The main method sets the root directory path.
  • It initializes an empty ArrayList to store all file paths.
  • It calls the listAllFiles method to recursively list all files in the root directory.
  • The listAllFiles method uses a DirectoryStream to iterate over the entries in the current directory.
  • For each entry, if it is a directory, the method recursively calls itself with the subdirectory path.
  • If it is a file, it adds the file path to the allFiles list.
  • At last, the allFiles list is printed to display all the found file paths.


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads