Java: FileFilter
javax.swing.filechooser.FileFilter
is used to restrict the files that are shown in
a JFileChooser.
By default, a file chooser shows all user files
and directories in a file chooser dialog, with the
exception of "hidden" files in Unix (those starting
with a '.'). You may restrict the list that is shown
by setting the file filter for a file chooser dialog.
Name Confusion. There are several file filtering classes and interfaces in Java, which often leads to confusion.
javax.swing.filechooser.FileFilter
- Use with JFileChooser. An abstract class that you must extend, defining accept(f) and getDescription().java.io.FileFilter
- Pass to the File listFiles(ff) method. An interface for which you must define accept(f).java.io.FilenameFilter
- Similar to java.io.FileFilter, in that your can call the File list(fnf) method, but apparently restricts the selection further to one name. Implementing this interface requires defining accept(dir, name). Doesn't seem to be as generally useful.
Setting a FileFilter
You need to create a file filter object by subclassing
the javax.swing.filechooser.FileFilter class and defining
the two methods accept
and getDescription
.
import javax.swing.*; . . . JFileChooser fc = new JFileChooser(); FileFilter filter = new FileFilter() { . fc.setFileFilter(FileFilter filter);
To display only specified extensions
This example
displays only .html
files.
Note that it's very important to also allow directories (f.isDirectory()
)
if you want the user to be able to move around the file system.
// File : fileutilstest/Test.java // Purpose: Restricts JFileChooser to show only HTML files. // Author: Fred Swartz // Date: 2005-02-25 import java.io.*; class HTMLFileFilter extends javax.swing.filechooser.FileFilter { public boolean accept(File f) { return f.isDirectory() || f.getName().toLowerCase().endsWith(".html"); } public String getDescription() { return ".html files"; } }
For this to work, be sure that the file chooser looks at both files and directories.
fc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
Setting a list of user selectable file filters
In an output file dialog, the user is sometimes presented with a choices of the format to save a file. These choosable file filters can be set and examined with:
fc.addChoosableFileFilter(FileFilter filter); filter = fc.getFileFilter();
Don't use ...
You will not use java.io.FileFilter
or
java.io.FilenameFilter
for a file chooser
dialog - they have other uses.