Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FilenameFilter to show list files with certain extension and directories

Tags:

java

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?

like image 839
matip Avatar asked Oct 18 '25 19:10

matip


1 Answers

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();
            }
        });
like image 65
ttzn Avatar answered Oct 22 '25 01:10

ttzn