Java FilenameFilter

I have a requirement to get all the files in a directory with a specific extension (e.g. .txt). I should be able to list all files with the extension ".txt" and ".TXT" (ie It should be case insensitive). I wrote the following class for this. What change should I make in the next 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 accept() , but that didn't work.

Thanks in advance.

+7
source share
1 answer

You also need to enter a lowercase letter.

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

It might also be a good idea to check the constructor to see if there is already a lead. and do not add another if so.

+14
source

All Articles