I am using FilenameFilter class to list all files with certain extension in the directory. But I would also like to list all the directories in that directory. I searched through the internet and found out only how to use FilenameFilter for multiple extensions. But how can I do that also with directories?
Here is code that I use to list all .txt files:
File[] listOfFiles = folder.listFiles(new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.toLowerCase().endsWith(".txt");
}
});
Is there even a way to do it via filter or do I have to do it in some other way?
You have many ways of doing this. In particular, a java.io.FileFilter
gives you more flexibility than a FilenameFilter
, allowing you to test for directories using isDirectory()
:
File[] listOfFiles = folder.listFiles(new FileFilter() {
@Override
public boolean accept(File pathname) {
return pathname.getName().toLowerCase().endsWith(".txt")
|| pathname.isDirectory();
}
});
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