Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 680
user957183 Avatar asked Nov 22 '11 09:11

user957183


People also ask

What is FilenameFilter in Java?

java.io.FilenameFilter. Instances of classes that implement this interface are used to filter filenames. These instances are used to filter directory listings in the list method of class File , and by the Abstract Window Toolkit's file dialog component.

How to Match File name Pattern in Java?

Once we obtain an interface to the filesystem by invoking the getDefault() method, we use the getPathMatcher() method from the FileSystem class. This is where we apply glob patterns on the individual file paths within rootDir. In our case, we can use the resulting PathMatcher to get an ArrayList of matching filenames.


1 Answers

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.

like image 72
stevevls Avatar answered Nov 08 '22 06:11

stevevls