Mega Code Archive

 
Categories / Java Book / 004 File Stream
 

0267 Using FilenameFilter

To limit the number of files returned by the list( ) method by filename pattern, or filter: String[ ] list(FilenameFilter ffObj) ffObj is an object of a class that implements the FilenameFilter interface. FilenameFilter defines only a single method, accept( ), which is called once for each file in a list. Its general form is: boolean accept(File directory, String filename) The accept( ) method returns true for files in the directory specified by directory that should be included in the list, and returns false for those files that should be excluded. import java.io.File; import java.io.FilenameFilter; class ExtensionFilter implements FilenameFilter { String ext; public ExtensionFilter(String ext) { this.ext = "." + ext; } public boolean accept(File dir, String name) { return name.endsWith(ext); } } public class Main { public static void main(String args[]) { String dirname = "/java"; File f1 = new File(dirname); FilenameFilter only = new ExtensionFilter("html"); String s[] = f1.list(only); for (int i = 0; i < s.length; i++) { System.out.println(s[i]); } } }