find specific file type from folder and its sub folder

user2614607 picture user2614607 · Dec 5, 2013 · Viewed 12.1k times · Source

I am writing a method to get specific file type such as pdf or txt from folders and subfolders but I am lacking to solve this problem. here is my code

  // .............list file
    File directory = new File(directoryName);

    // get all the files from a directory
    File[] fList = directory.listFiles();

    for (File file : fList) {
        if (file.isFile()) {
            System.out.println(file.getAbsolutePath());
        } else if (file.isDirectory()) {
            listf(file.getAbsolutePath());
        }
    }

My current method list all files but I need specific files

Answer

Tim B picture Tim B · Dec 5, 2013

For a filtered list without needing recursion through sub directories you can just do:

directory.listFiles(new FilenameFilter() {
    boolean accept(File dir, String name) {
        return name.endsWith(".pdf");
    }});

For efficiency you could create the FilenameFilter ahead of time rather than for each call.

In this case because you want to scan sub folders too there is no point filtering the files as you still need to check for sub folders. In fact you were very nearly there:

File directory = new File(directoryName);

// get all the files from a directory
File[] fList = directory.listFiles();

for (File file : fList) {
    if (file.isFile()) {
       if (file.getName().endsWith(".pdf")) {
           System.out.println(file.getAbsolutePath());
       }
    } else if (file.isDirectory()) {
        listf(file.getAbsolutePath());
    }
}