2016-11-15 94 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。您需要更改此变量以反映您实际想要匹配的任何扩展名。

相关问题