Free Data Structures and Algorithms Course









Subscribe below and get all best seller courses for free !!!










OR



Subscribe to all free courses

How to search for files in a directory based on extension using Apache commons-io API in Java ?

Program to demonstrate how to search for files in a directory based on extension using Apache commons-io API in Java.

package com.hubberspot.apache.commons.examples;

import java.io.File;
import java.util.Collection;
import java.util.Iterator;
import org.apache.commons.io.FileUtils;

public class RecursiveFileSearch {

    public static void main(String[] args) {

        // Create a File object and pass path of the directory
        // where files need to be searched
        File file = new File("D:/files");

        try {
            // an array of files extensions to be searched in 
            // the file created above.
            String[] extOfTheFiles = {"jar", "java", "pdf"};

            // FileUtils class of org.apache.commons.io
            // has a method by name listFiles() which takes in
            // three parameters the directory where files need to be 
            // searched , extension of the files to be searched and 
            // boolean value to make a recursive search for the files
            // The method returns back a collection of File objects
            Collection< File > listOfFiles= FileUtils.listFiles(file, extOfTheFiles, true);

            // Create a iterator for the collection of files
            Iterator< File > fileIterator = listOfFiles.iterator();

            // loop over each file in the collection
            while(fileIterator.hasNext()) {

                File searchedFile = fileIterator.next();

                // print the name of the file on the console
                System.out.println(searchedFile.getAbsolutePath());
            }

        } catch (Exception e) {
            e.printStackTrace();
        }        

    }

}



Output of the program :


 
© 2021 Learn Java by Examples Template by Hubberspot