Java Readers and Writers  «Prev  Next»


Lesson 7 Filename filters
ObjectiveWrite a Program that only displays text, HTML, and Java files in a file Dialog Box.

Java Filename Filters

You can set a FileDialog to point at a particular file using this code:
setFile(String filename)

However, if you already know the filename, why do you need to bring up a file dialog box? More likely is that you will want to look for a particular type of file, for instance text files. To make this happen you need to use a FilenameFilter to specify which files you will accept.
This is the key method:
setFilenameFilter(FilenameFilter fnf)

The java.io.FilenameFilter interface declares a single method:
public boolean accept(File dir, String name)

File dir

File dir is a directory, and String name is a filename. The method should return true if the file passes through the filter and false if it does not.
Since FilenameFilter is an interface, you must implement it in a class.
Files do not need to be filtered by filename only. You can test modification date, permissions, file size, and any attribute Java supports.
You cannot filter by attributes Java does not support, like Mac File and creator codes. The accept() method tests whether the file ends with .java and is in a directory to which you have write permission.

public boolean accept(File dir, String name) {
  if (name.endsWith(".java")
   && dir.canWrite()) return true;
  return false;
 }
FilenameFilter does not yet work on Windows. All files will appear in the dialog.

Files file Dialogs - Quiz

Click the Quiz link below to take a brief multiple-choice quiz on the File class, file dialog boxes, and filename filters.
Files file Dialogs - Quiz

Filename Filters - Exercise

When you have completed the quiz, return here and click the Exercise link below ro write a program that only displays text, HTML, and Java files in a file dialog box.
Filename Filters - Exercise