Ask Questions?

View Latest Questions


 
 

FileFilter
Posted on: July 26, 2006 at 12:00 AM
There are several file filtering classes and interfaces in Java.

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.g