Almighty Bus Error

Loading search...

Snippet.Java: Using FilenameFilter

To use a FilenameFilter it is needed to implement a method accept which has as arguments the directory where the file exists and the name of the file. It is normally used in conjuction with the list method of the File object.

The following example prints all the files with extension “jpg” in a certain directory:

public static void main(String[] args) {
    FilenameFilter filter = new FilenameFilter() {
        @Override
        public boolean accept(File dir, String name) {
            return name.endsWith(".jpg");
        }
    };

    for(String c : args) {
        File dir = new File(c);

        if(dir.isDirectory()) {
            System.out.println("Directory: " + c);
            for(String curr : dir.list(filter))
                System.out.println(curr);
        }
    }
}

More information can be found here.

Thank you for reading!