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


The FileFileFilter.FILE singleton instance in the ApacheSW Commons IOS library is a file filter that filters only files, not directories. Therefore, if we pass it as an argument in a call to a directory's listFiles() method, we'll obtain a listing of only the files in that directory. The ListFilesUsingFilterTest class demonstrates this.

ListFilesUsingFilterTest.java

package test;

import java.io.File;
import java.io.FileFilter;
import java.io.IOException;

import org.apache.commons.io.filefilter.FileFileFilter;

public class ListFilesUsingFilterTest {

	public static void main(String[] args) throws IOException {
		File directory = new File(".");

		System.out.println("All files and directories");
		File[] allFilesAndDirs = directory.listFiles();
		for (File f1 : allFilesAndDirs) {
			System.out.println(f1.getName());
		}

		System.out.println("\nOnly files");
		File[] onlyFiles = directory.listFiles((FileFilter) FileFileFilter.FILE);
		for (File f2 : onlyFiles) {
			System.out.println(f2.getName());
		}

	}

}

The execution of ListFilesUsingFilterTest is shown below. It first lists all files and directories at the root level of my project. It then lists only the files (no directories) at the root level of the project that were obtained using the FileFileFilter.FILE filter.

Results

All files and directories
.classpath
.project
bin
docs
lib
src
stuff

Only files
.classpath
.project


Related Tutorials: