Java program to find all files with given extension in a directory and its subdirectories

How to find all files with given extension in a directory and its subdirectories in Java:

In this post, we will learn how to find all files with a given extension in a folder and all of its subfolders. For example, I created a folder with files and sub-folders as like below:

Java find files recursively This directory is in another directory called test. We will pass this path of test and it will find all the files with extension .mp3 in all folders.

Recursive Approach:

We can solve this recursively. We can pass one list to a function and that function will add all files to the list. If it finds any directory, it will pass that directory to the function and recursively it will add all files with .mp3 extension to the list.

Below is the complete program:

import java.io.File;
import java.util.ArrayList;
import java.util.List;

public class Main {

    private static void getAllFiles(String path, List<String> fileList) {
        File[] allFiles = new File(path).listFiles();

        if (allFiles != null) {
            for (File file : allFiles) {
                if (file.isFile() && file.getName().endsWith(".mp3")) {
                    fileList.add(file.getName());
                } else if (file.isDirectory()) {
                    getAllFiles(file.getAbsolutePath(), fileList);
                }
            }
        }
    }

    public static void main(String[] args) {
        String path = "/Users/cvc/Downloads/test";
        List<String> fileList = new ArrayList<>();

        getAllFiles(path, fileList);

        System.out.println(fileList);
    }
}

Here,

  • getAllFiles method takes the path of the folder and one empty list fileList.
  • It gets all files in the folder using listFiles
  • For each file in the file list, it checks if the file ends with .mp3. If yes, it adds that file name to fileList.
  • If a directory is found, it calls that function recursively and finally all files with .mp3 extension are added to the list fileList.

Running the above program will print the below output:

[one.mp3, four.mp3, three.mp3, two.mp3]

You might also like: