List Files in Directory and Subdirectories in Java

Listing files in a directory and its subdirectories is a common requirement in Java. One of the best ways to do this is by using Java's Files class (introduced in Java 7) with the Files.walk() method. This method allows you to traverse directories and fetch all the files within them, making it particularly useful for such tasks. In this quick guide, we will see how to list files in a directory and its subdirectories in Java.

1. Using Files.walk()

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.stream.Collectors;

public class ListFiles {

    public static void main(String[] args) {
        Path startDir = Paths.get("path_to_directory");  // replace with your directory path

        try {
            List<Path> filesList = Files.walk(startDir)
                                        .filter(Files::isRegularFile)
                                        .collect(Collectors.toList());

            filesList.forEach(System.out::println);

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
The above method utilizes Java Streams. The Files.walk() method returns a stream of paths representing the directory and its subdirectories. Filtering with Files::isRegularFile ensures that only files (and not directories) are collected. 

2. Using File Class (Older Way) 

The older java.io.File class can also be used to recursively list files:
import java.io.File;
import java.util.ArrayList;
import java.util.List;

public class ListFilesOld {

    public static void main(String[] args) {
        File startDir = new File("path_to_directory");  // replace with your directory path
        List<File> filesList = new ArrayList<>();
        fetchFilesRecursively(startDir, filesList);

        for (File file : filesList) {
            System.out.println(file);
        }
    }

    public static void fetchFilesRecursively(File dir, List<File> allFiles) {
        File[] files = dir.listFiles();

        if (files == null) return;

        for (File file : files) {
            if (file.isDirectory()) {
                fetchFilesRecursively(file, allFiles);
            } else {
                allFiles.add(file);
            }
        }
    }
}
While this method is more verbose than the first one and doesn't utilize streams, it might be helpful when working with older versions of Java or in environments where java.nio isn't available. 

Both of the methods detailed above will provide a list of all files in the specified directory and its subdirectories.

Comments