How do I get all files in a directory including subdirectories using Commons IO?
Author: Deron Eriksson
Description: This Java tutorial describes how to get all files 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, IOFileFilter fileFilter, IOFileFilter dirFilter) method of the FileUtils class of the ApacheSW Commons IOS library returns a Collection of files in a specified directory passed in as its first parameter. If the third parameter (dirFilter) is null, only the files in the specified directory are returned. If TrueFileFilter.INSTANCE is passed in, all of the files within the specified directory are returned, including all subdirectories. This is illustrated by GetAllFilesInDirectory.

GetAllFilesInDirectory.java

package test;

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

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.filefilter.TrueFileFilter;

public class GetAllFilesInDirectory {

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

		File dir = new File("dir");

		System.out.println("Getting all files in " + dir.getCanonicalPath() + " including those in subdirectories");
		List<File> files = (List<File>) FileUtils.listFiles(dir, TrueFileFilter.INSTANCE, TrueFileFilter.INSTANCE);
		for (File file : files) {
			System.out.println("file: " + file.getCanonicalPath());
		}

	}

}

The GetAllFilesInDirectory class gets a Collection of all files within the "dir" directory, the contents of which are shown here:

'testing' project

The console output of GetAllFilesInDirectory is shown here. We can see that it returns all files within "dir", including subdirectories.

Getting all files in C:\projects\workspace\testing\dir including those in subdirectories
file: C:\projects\workspace\testing\dir\anotherdir\commons-codec-1.3.jar
file: C:\projects\workspace\testing\dir\anotherdir\log4j-1.2.14.jar
file: C:\projects\workspace\testing\dir\commons-io-1.4.jar
file: C:\projects\workspace\testing\dir\commons-net-1.4.1.jar


Related Tutorials: