matip matip - 1 year ago 60
Java Question

FilenameFilter to show list files with certain extension and directories

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?

Answer Source

You have many ways of doing this. In particular, a gives you more flexibility than a FilenameFilter, allowing you to test for directories using isDirectory() :

File[] listOfFiles = folder.listFiles(new FileFilter() {
            public boolean accept(File pathname) {
                return pathname.getName().toLowerCase().endsWith(".txt") 
                    || pathname.isDirectory();