dimo414
dimo414

Reputation: 48804

What is the benefit of FileFilter / FilenameFilter

Working on a small Java tool to get a set of files based on a set of filename extensions, I'm debating between using listFiles() and using continue; when I encounter a bad file, vs. using a custom FileFilter or FilenameFilter to do effectively the same for me.

It seems to me these methods are convenience methods for integrated tools like Swing file browsing, and are not any more efficient than the manual method if we're not hooking into any of those tools. Is that correct? Are there any other benefits to these filter tools?

Upvotes: 3

Views: 3750

Answers (4)

Thilo
Thilo

Reputation: 262474

Yes, they are mostly meant for tools that accept file filters (or in general anywhere the code that determines the logic is different from the code that does the evaluation of the filter). There is no magic under the hood, they just do what you could do in your own loop.

Upvotes: 1

Lukas Eder
Lukas Eder

Reputation: 220762

Like any other API based on interfaces, this allows for great reuse of logic. You can have the java.io.* API find files of any type for you, especially if you use libraries such as Apache Commons IO:

http://commons.apache.org/io/api-1.4/org/apache/commons/io/filefilter/package-summary.html

Upvotes: 2

Valentin Rocher
Valentin Rocher

Reputation: 11669

From the JDK 1.6 source :

public String[] list(FilenameFilter filter) {
    String names[] = list();
    if ((names == null) || (filter == null)) {
        return names;
    }
    ArrayList v = new ArrayList();
    for (int i = 0 ; i < names.length ; i++) {
        if (filter.accept(this, names[i])) {
            v.add(names[i]);
        }
    }
    return (String[])(v.toArray(new String[v.size()]));
}

So, as you can see, basically, the same thing is done here as you would do with a manual test. The only thing it brings you is not having to reinvent the wheel, and if they suddenly find a much quicker way to do it, you won't have to change your code :)

Upvotes: 2

Nico Huysamen
Nico Huysamen

Reputation: 10417

Nope, think you've got it right on the money there. They are convenience methods. They simply take a name, (and know the extension you set initially), and does a check to see if it should be included in the list of not. Much the same as what you are doing anyway.

From the Java Documentation:

public boolean accept(File dir, String name)

Tests if a specified file should be included in a file list.

Which is exactly what you are doing anyway.

Upvotes: 0

Related Questions