Platinum Partner

Java: Recursive ListFiles With Filter

Java's File class provides listFiles for listing all files in a directory but this does not recurse into subdirectories. This implementation does with an optional filter:

NB: This uses Java5 features such as foreach loop and generics but these can be removed to work with Java4 (see comments)


public static File[] listFilesAsArray(
		File directory,
		FilenameFilter filter,
		boolean recurse)
{
	Collection files = listFiles(directory,
			filter, recurse);
//Java4: Collection files = listFiles(directory, filter, recurse);
	
	File[] arr = new File[files.size()];
	return files.toArray(arr);
}

public static Collection listFiles(
// Java4: public static Collection listFiles(
		File directory,
		FilenameFilter filter,
		boolean recurse)
{
	// List of files / directories
	Vector files = new Vector();
// Java4: Vector files = new Vector();
	
	// Get files / directories in the directory
	File[] entries = directory.listFiles();
	
	// Go over entries
	for (File entry : entries)
	{
// Java4: for (int f = 0; f < files.length; f++) {
// Java4: 	File entry = (File) files[f];

		// If there is no filter or the filter accepts the 
		// file / directory, add it to the list
		if (filter == null || filter.accept(directory, entry.getName()))
		{
			files.add(entry);
		}
		
		// If the file is a directory and the recurse flag
		// is set, recurse into the directory
		if (recurse && entry.isDirectory())
		{
			files.addAll(listFiles(entry, filter, recurse));
		}
	}
	
	// Return collection of files
	return files;		
}
{{ tag }}, {{tag}},

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}
{{ parent.authors[0].realName || parent.author}}

{{ parent.authors[0].tagline || parent.tagline }}

{{ parent.views }} ViewsClicks
Tweet

{{parent.nComments}}