Search code examples
javaswingfilejfilechooserfilefilter

Filtering and selecting files from a directory


I have an application right now that selects files from a directory. what I want to do is be able to have a feature where you can put in a file extension such as .gif, .txt etc.. and after a button is clicked the application will run through the directory and find and select all files of that type. The only code I have to show is of my current application which has none of this. Was hoping for a point in the right direction or some advice.


Solution

  • private List<File> getMatchingFiles(File parent, final String extension) {
        File[] files = parent.listFiles(new FileFilter() {
    
            public boolean accept(File dir) {
                String name = dir.getName();
                if(name.endsWith(extension)) {
                    return true;
                }
            }
        });
    
        List<File> retval = Arrays.asList( files );
        return retval;
    }