Skip to content

Instantly share code, notes, and snippets.

@eman41
Last active December 16, 2015 09:49
Show Gist options
  • Save eman41/5415632 to your computer and use it in GitHub Desktop.
Save eman41/5415632 to your computer and use it in GitHub Desktop.
List all files in a directory with an extension filter. [Java 7]
package org.eman.gist;
import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.util.Collection;
import java.util.Arrays;
/**
* Print out a list of all files with a particular extension from a directory.
* @author eman41
*/
public class ListAllWithExtension
{
public static void main(String[] args) throws IOException
{
// Good candidates for command line args!
String srcPath = "C:/folder/containing/stuff";
final String ext = ".txt";
File src = new File(srcPath);
File[] fileArr = src.listFiles(new FilenameFilter()
{
@Override
public boolean accept(File dir, String name)
{
System.out.println(name); // Printing here, better off with a log!
return name.endsWith(ext);
}
});
// Dumping into a collection just for show
Collection<File> files = Arrays.asList(fileArr);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment