user957183
user957183

Reputation: 437

Java FilenameFilter

I have a requirement to get all of the files in a directory that have a specific extension(say, .txt). I should be able to list all of the files that have '.txt' and '.TXT' extension (i.e., it should be case insensitive). I've written the following class for this. What change should I make in the following class to achieve this?

class OnlyExt implements FilenameFilter {
    String ext;

    public OnlyExt(String ext) {
        this.ext = "." + ext;
    }

    public boolean accept(File dir, String name) {
        return name.endsWith(ext);
    }
}

Well, I tried name.toLowerCase().endsWith(ext); in the accept(), but that didn't work.

Thanks in advance.

Upvotes: 7

Views: 7909

Answers (1)

stevevls
stevevls

Reputation: 10843

You need to lowercase the extension, too.

class OnlyExt implements FilenameFilter {
    String ext;

    public OnlyExt(String ext) {
        this.ext = ("." + ext).toLowerCase();
    }

    public boolean accept(File dir, String name) {
        return name.toLowerCase().endsWith(ext);
    }
}

Also, it might be a good idea to check in the constructor to see if there's already a leading "." and not prepend another if so.

Upvotes: 14

Related Questions