How do I use a FileFilter to display only the directories within a directory?
Author: Deron Eriksson
Description: This Java tutorial describes how to use a FileFilter to display only the directories in a directory.
Tutorial created using: Windows XP || JDK 1.5.0_09 || Eclipse Web Tools Platform 2.0 (Eclipse 3.3.0)


In another tutorial, we saw how we could get the contents of a directory by using a File object's listFiles() method to get an array of File objects. We can create a filter so that we can select a subset of these results.

The File object has a listFiles method that takes as a parameter an object that implements the FileFilter interface. This interface requires us to implement one method, the accept method, that takes a File object as a parameter and returns a boolean. If this method returns true for a file, the file passed the filter. If it returns false, the file did not pass the filter.

I created a directoryFilter object that implements the FileFilter interface, and I implemented the accept method. The method returns true is the passed-in file is a directory and false if it is not a directory.

The call to f.listFiles() passes the directoryFilter as an argument.

DirectoryContents.java

package test;

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

public class DirectoryContents {

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

		File f = new File("."); // current directory

		FileFilter directoryFilter = new FileFilter() {
			public boolean accept(File file) {
				return file.isDirectory();
			}
		};

		File[] files = f.listFiles(directoryFilter);
		for (File file : files) {
			if (file.isDirectory()) {
				System.out.print("directory:");
			} else {
				System.out.print("     file:");
			}
			System.out.println(file.getCanonicalPath());
		}

	}

}

Executing DirectoryContents results in the following console output. Even though regular files are also present in the C:\projects\workspace\testing\ directory, they do not show up since they are not directories.

directory:C:\projects\workspace\testing\bin
directory:C:\projects\workspace\testing\f1
directory:C:\projects\workspace\testing\folder
directory:C:\projects\workspace\testing\lib
directory:C:\projects\workspace\testing\src

Related Tutorials: