Filename Filters

You often want to look for a particular kind of file—for example, text files. To do this, you need a FilenameFilter object that specifies which files you’ll accept. FilenameFilter is an interface in the java.io package:

public interface FilenameFilter

This interface declares a single method, accept():

public abstract boolean accept(File directory, String name);

The directory argument is a File object pointing to a directory, and the name argument is the name of a file. The method should return true if a file with this name in this directory passes through the filter and false if it doesn’t. Because FilenameFilter is an interface, it must be implemented in a class. Example 12.6 is a class that filters out everything that is not an HTML file.

Example 12-6. HTMLFilter

import java.io.*;

public class HTMLFilter implements FilenameFilter {

 public boolean accept(File directory, String name) {
 
   if (name.endsWith(".html")) return true;
   if (name.endsWith(".htm")) return true;
   return false;
 }
}

Files can be filtered using any criteria you like. An accept() method may test modification date, permissions, file size, and any attribute Java supports. (You can’t filter by attributes Java does not support, like Macintosh file and creator codes, at least not without native methods or some sort of access to the native API.) This accept() method tests whether the file ends with .html and is in a directory where the program can read files:

public boolean accept(File directory, String name) ...

Get Java I/O now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.