2014-09-05 73 views
0

當我運行這個方法時,我立即得到一個堆棧溢出異常,所以顯然該方法一直遞歸調用自己,但我不知道爲什麼。作爲參考的文件結構我與測試它是文件夾的負載,並在這些文件夾是文件,沒有其他文件夾來自遞歸目錄遍歷的堆棧溢出錯誤

public void files(File[] f) 
    { 
    if(f == null){ 
     return; 
    } 
    else 
    { 
    for(int i = 0; i < f.length; i++) 
    { 
     if(f[i].isFile() && (f[i].getName().contains(".mp3") || f[i].getName().contains(".m4a"))) //iterate through files and check if each file matches the required criteria 
     { 
       String fullname = f[i].getName(); 
       Log.v("full name", fullname); 
       String name = null; 
       if(fullname.contains(".mp3")) 
       { 
       name = fullname.substring(0, fullname.lastIndexOf(".mp3")); 
       } 
       else if(fullname.contains(".m4a"))         //Removing file extensions of music file so they can be displayed using an appropriate name 
       { 
        name = fullname.substring(0, fullname.lastIndexOf(".m4a")); 
       } 
       list.add(name); 
       mp3.add(f[i]); 
       Log.v("added", name); 
     } 
     if(f[i].isDirectory()) 
     { 
      File inner[] = files[i].listFiles(); 
      files(inner); 
     } 

    } 
    } 

    } 
+0

我會做的第一件事是添加更多的日誌記錄。接下來我要做的是將遞歸調用改爲接受*一個*文件 - 僅僅因爲處理起來更簡單。 – 2014-09-05 20:57:50

+0

嘗試使用4個文件夾和相當多的文件,並工作 – EatBearsForBreakfast 2014-09-05 21:15:28

回答

0

也許有些文件是「」和「..」這意味着,我認爲,當前文件夾和返回一個文件夾。

因此,在你的isDirectory()部分if檢查時還要檢查f [i]!=「。」。和f [i] = 「..」

if(f[i].isDirectory() and f[i]!="." and f[i]!="..") 
    { 
     File inner[] = files[i].listFiles(); 
     files(inner); 
    } 

編輯:!

正如@喬恩說,嘗試更多的調試添加到它,看看它究竟打破。

以後編輯:

對於未來的讀者,問題在這裏:

//File inner[] = files[i].listFiles(); 
    File inner[] = f[i].listFiles(); 
+0

這是我的第一個想法,寫它,然後刪除它,因爲listFiles的javadocs明確地說。並沒有退回。 http://docs.oracle.com/javase/7/docs/api/java/io/File.html#listFiles() – 2014-09-05 21:19:47

+1

我剛剛注意到這一點,誰是文件[我],不應該是f [我]? – 2014-09-05 21:25:26

+0

我不知道爲什麼這是downvoted。 +1 – Cratylus 2014-09-05 21:26:26

0

我的一部分,所以超級愚蠢的錯誤,從以前的非遞歸實現複製代碼時,我忘了改文件到f在

if(f[i].isDirectory()) 
     { 
      File inner[] = files[i].listFiles(); 
      files(inner); 
     }