find specific file type from folder and its sub folder

13k views Asked by At

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

6

There are 6 answers

0
Memran On BEST ANSWER
if(file.getName().endsWith(".pdf")) {
    //it is a .pdf file!
}

/***/

4
Tim B On

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());
    }
}
0
Seelenvirtuose On

Use File.listFiles(FileFilter).

Example:

File[] fList = directory.listFiles(new FileFilter() {
    @Override
    public boolean accept(File file) {
        return file.getName().endSwith(".pdf");
    }
});
0
asafm On

Try using the FilenameFilter interface in you function http://docs.oracle.com/javase/6/docs/api/java/io/FilenameFilter.html

http://www.mkyong.com/java/how-to-find-files-with-certain-extension-only/ - for a code that has extention filter

0
Karthik Prasad On

You can use apache fileUtils class

String[] exte= {"xml","properties"};
Collection<File> files = FileUtils.listFiles(new File("d:\\workspace"), exte, true);

for(File file: files){
     System.out.println(file.getAbsolutePath());
}
0
luca On

My advice is to use FileUtils or NIO.2.
NIO.2 allows Stream with Depth-First search, for example you can print all files with a specified extension in one line of code:

Path path = Path.get("/folder");
try{
    Files.walk(path).filter(n -> n.toString().endsWith(".extension")).forEach(System.out::println)
}catch(IOException e){
    //Manage exception
}