2012-06-26 45 views
1

可能重複顯示的問題:
Delete a folder on SD card同時刪除目錄

在我的應用我保存使用內部存儲即文件中的所有我的數據。所以在第一個例子中,通過使用ContextWrapper cw = new ContextWrapper(getApplicationContext());類,我得到的目錄路徑爲m_AllPageDirectoryPath = cw.getDir("AllPageFolder", Context.MODE_PRIVATE);在這個目錄路徑中,我保存了一些文件File Page01,page02,Page03等等。

再次在裏面Page01我保存了一些文件,如image01,image02 ...使用相同的概念m_PageDirectoryPath = cw.getDir("Page01", Context.MODE_PRIVATE);現在刪除m_AllPageDirectoryPath我想刪除所有與之關聯的文件。我試過使用這個代碼,但它不起作用。

File file = new File(m_AllPageDirectoryPath.getPath()); 
file.delete(); 

回答

2

你的代碼,只有當你的目錄爲空工作。

如果目錄包含文件和子目錄,那麼你必須刪除所有文件遞歸 ..

試試這個代碼,

// Deletes all files and subdirectories under dir. 
// Returns true if all deletions were successful. 
// If a deletion fails, the method stops attempting to delete and returns false. 
public static boolean deleteDir(File dir) { 
    if (dir.isDirectory()) { 
     String[] children = dir.list(); 
     for (int i=0; i<children.length; i++) { 
      boolean success = deleteDir(new File(dir, children[i])); 
      if (!success) { 
       return false; 
      } 
     } 
    } 

    // The directory is now empty so delete it 
    return dir.delete(); 
} 

(其實你要問之前互聯網上搜索像這樣的問題)

+0

+1首先刪除所有文件和刪除目錄的好概念 – Lucifer

+0

我的目錄文件夾結構是這樣的。 MainDirectory-> haveMoreTheOneSubdirectory-> HaveMoreThenOneFile..so我想要刪除特定的子目錄及其文件 – AndroidDev

+0

上面的代碼刪除你將在參數中給出的目錄。 – user370305