Generic File Filter : FileFilter « File « Java Tutorial






import java.io.File;

import javax.swing.filechooser.FileFilter;

public class GenericFileFilter extends FileFilter {
  private String[] fileExts;

  private String description;

  private String extension;

  public GenericFileFilter(String[] filesExtsIn, String description) {
    fileExts = filesExtsIn;

    this.description = description;
  }

  public boolean accept(File f) {
    if (f.isDirectory()) {
      return true;
    }
    extension = getExtension(f);
    if (extension != null) {
      for (int i = 0; i < fileExts.length; i++) {
        if (check(fileExts[i]))
          return true;
      }
    }
    return false;
  }

  private boolean check(String in) {
    return extension.equalsIgnoreCase(in);
  }

  public String getDescription() {
    return description;
  }

  private String getExtension(File file) {
    String filename = file.getName();
    int length = filename.length();
    int i = filename.lastIndexOf('.');
    if (i > 0 && i < length - 1)
      return filename.substring(i + 1).toLowerCase();
    return null;
  }
}








11.72.FileFilter
11.72.1.Create custom File filter
11.72.2.List file with file filter
11.72.3.Custom File Filter
11.72.4.Filter by file
11.72.5.This filter accepts Files that are directories
11.72.6.Filters files based on the extension (what the filename ends with)
11.72.7.Inverted File Filter
11.72.8.Files filter that filters files by their suffix (or extension)
11.72.9.Generic File Filter
11.72.10.A suffix based file filter.