2017-04-15 67 views
0

我正在嘗試編寫一個代碼,用於搜索所選文件夾中所有包含文件名中包含特定單詞的文檔/圖形擴展名的文件。我找不到任何similiar例子,我試過這個1是最接近的幾種不同的方法:在java中使用擴展名和通配符搜索進行遞歸文件搜索

private void startButtonActionPerformed(java.awt.event.ActionEvent evt) {            

    File startingPath = dirChooser.getCurrentDirectory(); 
    String[] extensions = new String[] { 
     "txt", "doc", "docx", "jpg", "jpeg", "pdf", "odt", "png", "bmp"}; 
    // there are about 20 different patterns like the ones below 
    Pattern p = Pattern.compile(".*password.*|.*user.*|.*profile.*"); 
    List<File> files = (List<File>) FileUtils.listFiles(
       startingPath, extensions, true); 
    files.forEach((file) -> { 
     if (file.isFile()){ 
      Matcher m = p.matcher(file.toString().toLowerCase()); 
      if (m.matches()) { 
       filesArea.append(file.toString() + "\n"); 
       noOfFiles++; 
      }  
     } 
    }); 
} 

的擴展搜索的工作完美,但出於某種原因,模式的搜索只適用於某些文件夾,而不是別人。我相信有更好的方法,但這似乎是最簡單和(幾乎)工作。任何想法如何讓它充分發揮作用?

回答

0

怎麼樣:

Files.walk(dirChooser.getCurrentDirectory().toPath()) 
    .filter(file -> Pattern.matches(".*password.*|.*user.*|.*profile.*", file.getFileName().toString()) && accept(file)) 
    .forEach(System.out::println); 

接受函數看起來像:

public boolean accept(Path e) 
{ 
    FileNameExtensionFilter filter = new FileNameExtensionFilter("Extensions", "txt", "doc", "docx", "jpg", "jpeg", "pdf", "odt", "png", "bmp"); 
    return filter.accept(e.toFile()); 
} 

該代碼將列出一個路徑包含您的字和特定擴展名的文件。然而,它是一個流,所以你可以用它來做任何你想要的。

+0

對不起,延遲迴復,它的工作,謝謝! – momp