2016-11-15 115 views
-1

我被給了一些僞代碼來讓我去,但我無法弄清楚它全部。擴展被賦給變量「分機」遞歸地顯示具有特定擴展名的所有文件

If f.isFile() is true, then 
If f.getPath() ends with the extension, then 
    Add f.getPath() to the foundFiles array list 
Return // this is the end of recursion 
Else // This must be a directory 
For each subFile in f.listFiles() // This gets all the files in the directory 
    Call findMatchingFiles(subFile) // This is the recursive call 

這是我迄今爲止,並似乎無法填補空白。任何提示或幫助非常感謝。

public void findMatchingFiles(File f) { 

    if (f.isFile() == true) { 
     if() { 

     foundFiles.add(f.getPath()); 
     } 

     return; 
    } else { 
     for (:) { 
      findMatchingFiles(subFile); 
     } 

    } 

} 
} 

回答

0
public void findMatchingFiles(File f) { 

    //i added this. you need to change it to be whatever extension you want to match 
    String myExtension = ".exe"; 

    if (f.isFile() == true) { 

     //i added this block. it gets the extension and checks if it matches 
     int i = fileName.lastIndexOf('.'); 
     String extension = fileName.substring(i+1); 
     if (extension.equals(myExtension)) { 
      foundFiles.add(f.getPath()); 
     } 
     return; 
    } else { 

     //i added this. it gets all the files in a folder 
     for (File subFile : f.listFiles()) { 
      findMatchingFiles(subFile); 
     } 
    } 
} 

上面的代碼應該解決您的問題。你錯過的兩件事是:

  1. 如何獲取文件夾中的文件。谷歌搜索發現此:Getting the filenames of all files in a folder
  2. 如何獲取文件擴展名。谷歌搜索發現:How do I get the file extension of a file in Java?

我把這兩個插入到你的代碼,它應該工作正常。還要注意我添加的變量名爲myExtension。您需要更改此變量以反映您實際想要匹配的任何擴展名。

相關問題