How do I get the directories in a directory using a filter?
Author: Deron Eriksson
Description: This Java tutorial describes how to get the directories 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 DirectoryFileFilter.DIRECTORY singleton instance is a directory filter in the ApacheSW Commons IOS library that can be used to filter only directories so that if we call a directory's listFiles() method, we'll only get back the directories within that directory. This is illustrated by the ListSubdirectoriesUsingFilterTest class.

ListSubdirectoriesUsingFilterTest.java

package test;

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

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

public class ListSubdirectoriesUsingFilterTest {

	public static void main(String[] args) throws IOException {
		File directory = new File(".");
		File[] subdirs = directory.listFiles((FileFilter) DirectoryFileFilter.DIRECTORY);
		for (File dir : subdirs) {
			System.out.println("Directory: " + dir.getName());
		}

	}

}

The ListSubdirectoriesUsingFilterTest class lists all of the directories within the root directory of my project. The console output is shown below:

Results

Directory: bin
Directory: docs
Directory: lib
Directory: src
Directory: stuff


Related Tutorials: