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 java.io.File 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.io.File;
import java.io.FileFilter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author sanju.org
 * @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){
			System.out.println(file.getAbsolutePath());
		}
	}

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

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

}
----------------------------------------------------------------------------------
package org.sanju;

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

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
/local/opt/apache-activemq-5.2.0
/local/opt/apache-ant-1.7.1
/local/opt/apache-tomcat-6.0.18-src
/local/opt/apache-tomcat-6.0.32
...............
.............

Advertisements

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:

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s

%d bloggers like this: