GenericFileFilter.java Source code

Java tutorial

Introduction

Here is the source code for GenericFileFilter.java

Source

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;
    }
}