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.
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.