Open In App

List all Files from a Directory Recursively in Java

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:



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

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




// 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.

Explanation of the above Program:


Article Tags :