rogerthat
rogerthat

Reputation: 1815

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.

Upvotes: 1

Views: 3186

Answers (4)

Andrew Thompson
Andrew Thompson

Reputation: 168825

For use in a JFileChooser, all the answers so far offered are sub-optimal. Instead implement JFileChooser.setFileFilter(javax.swing.filechooser.FileFilter) for the best user experience.

It might end up looking something like this1:

JFileChooser with file filters

  1. Image obtained using code courtesy of A Sample FileChooser Program.

Upvotes: 3

yydonny
yydonny

Reputation: 21

What you are looking for is probably the java.io.File#list(filter).

edit: If you want the entire file system be searched, then you need to recursively scan every direcotry:

public static void filter (String dirname, List<File> result) {
    try {
        for (String f : new File(dirname).list()) {
            String filename = dirname + f;
            File theFile = new File(filename);
            if (theFile.isDirectory()) {
                filter(filename + "/", result);
            } else if (new FileFilter() {
                public boolean accept(File pathname) {
                    return pathname.getName().endsWith(".gif");
                }
            }.accept(theFile)) {
                result.add(theFile);
            }
        }
    } catch (Exception e) {
        // may raise null-pointer when access denied
    }
}

public static void main(String[] args) {
    List<File> result = new ArrayList<File>();
    filter("F:/", result);

    System.out.println(result.size());
}

Upvotes: 2

Shamis Shukoor
Shamis Shukoor

Reputation: 2515

FilenameFilter filter = new FilenameFilter() {
  public boolean accept(File dir, String name) {
   return (!name.endsWith(".gif") 
    }
};

Upvotes: 1

Capn Sparrow
Capn Sparrow

Reputation: 2070

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;
}

Upvotes: 3

Related Questions