Clean Java

There is always a bigger game

How to list all directories in java?

leave a comment »

If you want to list out all files in a directory or drive you can use the list method in the class. Consider a scenario where you wanted to list out all directries. Today we will look at the use of FileFilter interface with a simple example. Given below example will recursively list out all directories in the given location.

package org.sanju;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

 * @author
 * @date 31st July, 2011
 * How to filter file in java?
 * FileFilter example in java.

public class FileFilteringExample {

	public static void main(String args[]){
		FileFilter filter = new DirectoryFilter();
		List javaFiles = new ArrayList();
		new FileFilteringExample().findUsingExtension(new File(
				"/local/opt"), filter, javaFiles);

		System.out.println("Found "+javaFiles.size()+" java files in /local/opt");
		for(File file : javaFiles){

	private void findUsingExtension(File file, FileFilter filter, List files){
		if(file == null || filter == null || files == null)
			throw new IllegalArgumentException("Argument can't be null");

			File [] filteredFiles = file.listFiles(filter);
			if(null != filteredFiles){
			for(File childFile : file.listFiles()){
				if(null != childFile){
					findUsingExtension(childFile, filter, files);

package org.sanju;


public class DirectoryFilter implements FileFilter{

	public boolean accept(File pathname) {
		boolean accept = false;
		if(null != pathname){
			accept = pathname.isDirectory();
		return accept;

Console output
Found 7999 java files in /local/opt


Written by cleanjava

February 25, 2012 at 10:28 pm

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: