How do I get all files with certain extensions in a directory including subdirectories?
Author: Deron Eriksson
Description: This Java tutorial describes how to get all files with certain extensions in a directory including subdirectories using Commons IO.
Tutorial created using: Windows XP || JDK 1.5.0_09 || Eclipse Web Tools Platform 2.0 (Eclipse 3.3.0)


The listFiles(File directory, String[] extensions, boolean recursive) method of the FileUtils class of the ApacheSW Commons IOS library returns a Collection of files in the specified directory. If "extensions" is null, all files are returned. Otherwise, it specifies the extensions of the files to include in the Collection. If "recursive" is false, only files in the specified directory matching the extensions are included. If "recursive" is true, all of the files matching the extensions are included in the Collection, including those in all subdirectories.

The GetAllFilesInDirectoryBasedOnExtensions class illustrates this.

GetAllFilesInDirectoryBasedOnExtensions.java

package test;

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

import org.apache.commons.io.FileUtils;

public class GetAllFilesInDirectoryBasedOnExtensions {

	public static void main(String[] args) throws IOException {

		File dir = new File("dir");
		String[] extensions = new String[] { "txt", "jsp" };
		System.out.println("Getting all .txt and .jsp files in " + dir.getCanonicalPath()
				+ " including those in subdirectories");
		List<File> files = (List<File>) FileUtils.listFiles(dir, extensions, true);
		for (File file : files) {
			System.out.println("file: " + file.getCanonicalPath());
		}

	}

}

The GetAllFilesInDirectoryBasedOnExtensions class utilizes the "dir" directory, shown here.

'testing' project

The console output of GetAllFilesInDirectoryBasedOnExtensions is shown here. As we can see, it displays all jspW and txt files in "dir", including subdirectories.

Getting all .txt and .jsp files in C:\projects\workspace\testing\dir including those in subdirectories
file: C:\projects\workspace\testing\dir\anotherdir\hamburger.jsp
file: C:\projects\workspace\testing\dir\anotherdir\test2.txt
file: C:\projects\workspace\testing\dir\test1.txt


Related Tutorials: