从文件夹及其子文件夹中查找特定文件类型

use*_*607 3 java io file file-search

我正在编写一个方法来从文件夹和子文件夹中获取特定文件类型,如pdf或txt,但我不能解决这个问题.这是我的代码

  // .............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());
        }
    }
Run Code Online (Sandbox Code Playgroud)

我当前的方法列出所有文件,但我需要特定的文件

Tim*_*m B 9

对于不需要通过子目录递归的筛选列表,您可以这样做:

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

为了提高效率,您可以提前创建FilenameFilter而不是每次调用.

在这种情况下,因为您还要扫描子文件夹,所以无需过滤文件,因为您仍需要检查子文件夹.事实上你几乎就在那里:

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());
    }
}
Run Code Online (Sandbox Code Playgroud)


Mem*_*ran 6

if(file.getName().endsWith(".pdf")) {
    //it is a .pdf file!
}
Run Code Online (Sandbox Code Playgroud)

/ *** /