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 | Cafe au Lait

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