File Filters
The FileFilter interface is very similar to FilenameFilter:
public abstract interface FileFilter
The accept( ) method of FileFilter takes a single File object as an argument, rather than two strings giving the directory and path:
public boolean accept(File pathname)
Example 17-8 is a filter that only passes HTML files. Its logic is essentially the same as the filter of Example 17-7.
Example 17-8. HTMLFileFilter
import java.io.*; public class HTMLFileFilter implements FileFilter { public boolean accept(File pathname) { if (pathname.getName( ).endsWith(".html")) return true; if (pathname.getName( ).endsWith(".htm")) return true; return false; } } |
This class appears as an argument in one of the listFiles( ) methods of java.io.File:
public File[] listFiles(FileFilter filter)
Example 17-9 uses the HTMLFileFilter to list the HTML files in the current working directory.
Example 17-9. List HTML files
import java.io.*; public class HTMLFiles { public static void main(String[] args) { File cwd = new File(System.getProperty("user.dir")); File[] htmlFiles = cwd.listFiles(new HTMLFileFilter( )); for (int i = 0; i < htmlFiles.length; i++) { System.out.println(htmlFiles[i]); } } } |