簡體   English   中英

從文件夾及其子文件夾中查找特定文件類型

[英]find specific file type from folder and its sub folder

我正在編寫一個方法來從文件夾和子文件夾中獲取特定文件類型,如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());
        }
    }

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

對於不需要通過子目錄遞歸的篩選列表,您可以這樣做:

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

為了提高效率,您可以提前創建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());
    }
}
if(file.getName().endsWith(".pdf")) {
    //it is a .pdf file!
}

/ * ** /

使用File.listFiles(FileFilter)

例:

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

您可以使用apache fileUtils類

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

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

我的建議是使用FileUtilsNIO.2
NIO.2允許Stream使用Depth-First搜索,例如,您可以在一行代碼中打印具有指定擴展名的所有文件:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM