File Filters

Java 2 adds a new java.io.FileFilter interface that’s very similar to FilenameFilter:

public abstract interface FileFilter  // Java 2

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)  // Java 2

Example 12.7 is a filter that only passes HTML files. Its logic is essentially the same as the filter of Example 12.6.

Example 12-7. 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)      // Java 2

Example 12.8 uses the HTMLFileFilter to list the HTML files in the current working directory.

Example 12-8. 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]);
    }
  }
}

Note

There’s a nasty name conflict between the java.io.FileFilter interface and the abstract javax.swing.filechooser.FileFilter class discussed in the next chapter. I would not be surprised if this interface were replaced by a new abstract FileFilter class more ...

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.