How do I search for files recursively?

This example demonstrate how we can use the FileUtils class listFiles() method to search for a file specified by their extensions. We can also define to find the file recursively deep down into the subdirectories.

package org.kodejava.commons.io;

import org.apache.commons.io.FileUtils;

import java.io.File;
import java.util.Collection;

public class SearchFileRecursive {
    public static void main(String[] args) {
        File root = new File("F:/Wayan/Kodejava/kodejava-example");

        try {
            String[] extensions = {"xml", "java", "dat"};

            // Find files within a root directory and optionally its
            // subdirectories which match an array of extensions. When the
            // extensions are null all files will be returned.
            //
            // This method will return matched file as java.io.File
            Collection<File> files = FileUtils.listFiles(root, extensions, true);

            for (File file : files) {
                System.out.println("File = " + file.getAbsolutePath());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Maven Dependencies

<!-- https://search.maven.org/remotecontent?filepath=commons-io/commons-io/2.11.0/commons-io-2.11.0.jar -->
<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.11.0</version>
</dependency>

Maven Central

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.