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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With