How to get list of files with given extension in a directory using Java?

To find the list of files with a given extension (for e.g., ".exe") in a directory, use the following function in Java.

You need to pass the directory path and the extension as parameters to the function. It will return an array of files with the given extension in that directory.

public String[] getAllFiles(String baseDir, String type)
{
        final String EXTN = ".exe";
        File file = new File(baseDir);
        String files[] = null;

        if (type.equals(EXTN))
        {
                files = file.list(new FilenameFilter() {
                        public boolean accept(File dir, String name)
                        {
                                if (name.endsWith(EXTN))
                                        return true;
                                else
                                        return false;
                        }
                });
        }
        return files;
}

Search