Is there any better way to do filefilter for many ext?


File files[] = rootDir.listFiles(new FileFilter() {
    public boolean accept(File file) {
        if (file.isDirectory())
            return true;

    String name = file.getName().toLowerCase();

    if (name.endsWith(".zip") || name.endsWith(".jar")
     || name.endsWith(".z") || name.endsWith(".gz")
     || name.endsWith(".tar") || name.endsWith(".bz2")
     || name.endsWith(".bz"))
        return true;

    return false;
    }
});

As you can see, the code is dirty with "||"

Do you know how to make it better?


Answers:


With Java 6 or above, this is a perfect case for a FileNameExtensionFilter... except that it extends javax.swing.filechooser.FileFilter instead of implementing java.io.FileFilter.
But it is trivial to write a wrapper for it:

File[] files = rootDir.listFiles(new FileFilter() {
    private final FileNameExtensionFilter filter =
        new FileNameExtensionFilter("Compressed files",
            "zip", "jar", "z", "gz", "tar", "bz2", "bz");
    public boolean accept(File file) {
        return filter.accept(file);
    }
});