Filename Filters

java.io.FilenameFilter is an interface that declares single method,

public boolean accept(File directory, String filename)

The method should return true if the file passes through the filter and false if it doesn't.

Since FilenameFilter is an interface, you must implement it in a class. Here is an example class which filters out everything that is not a java source code file.

import java.io.*;

public class JavaFilter implements FilenameFilter {

 public boolean accept(File directory, String filename) {
 
   if (filename.endsWith(".java")) return true;
   return false;
 
 }

}
Files do not need to be filtered by filename only. You can test modification date, permissions, filesize and more. For example this accept method tests whether the file ends with .java and is in a directory to which you have write permission.

 public boolean accept(File directory, String filename) {
 
   if (filename.endsWith(".java") && directory.canWrite()) return true;
   return false;

 }

Previous | Next | Top
Last Modified December 5, 2000
Copyright 1997, 2000 Elliotte Rusty Harold
elharo@metalab.unc.edu