What need to do when you want to filter files by extensions in directory?
There are 2 ways:
implement FileFilter or FilenameFilter.
I am going to show how to do this with FileFilter.
FileFilter is an interface for filtering File objects based on their names or other information.
Example:
class ProjectFilter implements FileFilter{ private String[] extension ={"java","xml"}; @Override public boolean accept(File pathname){ if (pathname.isDirectory()){ return true; } String name = pathname.getName().toLowerCase(); for (String anExt:extension){ if (name.endsWith(anExt)){return true; } } return false; }}Now just use ProjectFilter object in listFiles method.
Example:
File dir = new File("C:/sample_dir");File[] files = dir.listFiles(new ProjectFilter())In this case in array files will presents files with extensions java and xml.
Full example:
import java.io.File;import java.io.FileFilter;public class Main{ public static void main(String[] args){ File dir = new File("D:/project/sample_dir"); File[] files = dir.listFiles(new ProjectFilter()); for (File f:files){ System.out.println(f.getAbsolutePath()); } } private static class ProjectFilter implements FileFilter{ private String[] extension ={"java","xml"}; @Override public boolean accept(File pathname){ if (pathname.isDirectory()){return true; } String name = pathname.getName().toLowerCase(); for (String anExt:extension){if (name.endsWith(anExt)){return true;} } return false; } }}File filtering is very simple operation in Java.
For this post I used JDK 6.
No related posts.

Recent Comments