2014-03-31 17 views
2

我正在尋找作爲更大程序的一部分找到Java中特定文件夾的路徑。
我有一個遞歸函數,用於檢查啓動目錄中包含的每個文件,並且如果它發現我正在查找的文件夾,則將該路徑作爲字符串分配給變量。下面的代碼工作:在Java中查找特定的文件夾

//root is the starting directory and name is the folder I am looking for 
private void findDir(File root, String name) 
{ 
    if (root.getName().equals(name)) 
    { 
     toFind = root.getAbsolutePath(); 
    } 

    File[] files = root.listFiles(); 

    if(files != null) 
    { 
     for (File f : files) 
     { 
      if(f.isDirectory()) 
      { 
       findDir(f, name); 
      } 
     } 
    } 
} 

這工作,但我不喜歡的事實,我必須使用「找到相當」變量。我的問題是有沒有辦法讓方法返回一個字符串而不是void?這也將節省程序在找到正在查找的文件後檢查系統中的所有其他文件。
我在想這樣的事情,但下面的代碼將返回null,即使它找到該文件夾​​。

private String findDir(File root, String name) 
{ 
    if (root.getName().equals(name)) 
    { 
     return root.getAbsolutePath(); 
    } 

    File[] files = root.listFiles(); 

    if(files != null) 
    { 
     for (File f : files) 
     { 
      if(f.isDirectory()) 
      { 
       return findDir(f, name); 
      } 
     } 
    } 

    return null; //??? 
} 
+1

['Files'](http://docs.oracle.com/javase/7/docs/api/java/nio/file/Files.html)中的內置方法有什麼問題嗎?例如''walkFileTree()'。不要重新發明輪子。 –

+0

我會盡量通過使用walkFileTree()來做到這一點,但只有當我不能做遞歸。只是爲了我自己的滿意才這樣做。謝謝你的建議。 – PetarMI

回答

1

這是因爲在沒有子目錄樹的第一個目錄將返回null由於您指定如果listFiles()結果null,爲整個遞歸返回null的事實。這並不明顯,但可以通過更改for循環中的行爲來解決此問題。您不應該直接在for循環中返回結果,而應該測試結果是否爲null,如果是,則繼續。如果你有一個非空結果,你可以向上傳播結果。

private String findDir(File root, String name) 
{ 
    if (root.getName().equals(name)) 
    { 
     return root.getAbsolutePath(); 
    } 

    File[] files = root.listFiles(); 

    if(files != null) 
    { 
     for (File f : files) 
     { 
      if(f.isDirectory()) 
      { 
       String myResult = findDir(f, name); 
       //this just means this branch of the 
       //recursion reached the end of the 
       //directory tree without results, but 
       //we don't want to cut it short here, 
       //we still need to check the other 
       //directories, so continue the for loop 
       if (myResult == null) { 
        continue; 
       } 
       //we found a result so return! 
       else { 
        return myResult; 
       } 
      } 
     } 
    } 

    //we don't actually need to change this. It just means we reached 
    //the end of the directory tree (there are no more sub-directories 
    //in this directory) and didn't find the result 
    return null; 
} 

編輯:使用鮑里斯蜘蛛的建議,我們實際上可以剝離下來的if聲明,以避免continue聲明的有些笨重性質,使代碼更給了點一點。相反的:

if (myResult == null) { 
    continue; 
} 
else { 
    return myResult; 
} 

我們可以只滑倒在它的地方:

if (myResult != null) { 
    return myResult; 
} 

這將完全相同的邏輯評估和花費較少的總體代碼。

+0

謝謝,那就是我正在尋找的!在我看來非常優雅的解決方案。 – PetarMI

+1

你不需要'繼續' - 如果污染的東西。只要'myResult!= null'返回''。 –

+0

@BoristheSpider誠然,你不需要'continue',並且'if'語句可以被重寫,但是我更喜歡簡潔性的可讀性,其實這只是一個風格問題。 – Sam

相關問題