Delete folder from internal storage in android?

谁都会走 提交于 2019-12-03 11:21:39

问题


How to delete folder(contain some folder and file) from internal storage? Folder have some below tree.

folder
|_________  C2 (folder)
             |________1 (folder)
                      |________1.gif
                      |________2.gif
                      |________3.gif
                      |________4.gif
             |________2 (folder)
                      |________1.gif
                      |________2.gif
                      |________3.gif
                      |________4.gif
             |________3 (folder)
                      |________1.gif
                      |________2.gif
                      |________3.gif
                      |________4.gif
             |________4 (folder)
                      |________1.gif
                      |________2.gif
                      |________3.gif
                      |________4.gif
             |________5 (folder)
                      |________1.gif
                      |________2.gif
                      |________3.gif
                      |________4.gif

|_________  C2.xml (file)

I want to delete folder and containing all files

fil.delete();

System.out.println("boolean =>" + fil.delete());

but above code shows false. Please help.


回答1:


Check this out.

public void deleteRecursive(File fileOrDirectory) {

   if (fileOrDirectory.isDirectory()) {
       for (File child : fileOrDirectory.listFiles()) {
          deleteRecursive(child);
       }
   }

   fileOrDirectory.delete();
 }

for explaination How to delete a whole folder and content?




回答2:


You can't delete root folder if sub folder contains any files. So for that you have to first delete each of sub files and then you will able to remove the folder.

Your code is valid, I just update like:

 boolean deleted = mypath.delete();

ie. mypath is your File Directory.




回答3:


Let me tell you first thing you cannot delete the Rootfolder because it is a system folder. As you delete it manually on phone it will delete the contents of that folder, but not the Root folder. You can delete its contents by using the method below:

private void DeleteRecursive(File fileOrDirectory) {
    if (fileOrDirectory.isDirectory())
        for (File child : fileOrDirectory.listFiles())
        {
            child.delete();
            DeleteRecursive(child);
        }

    fileOrDirectory.delete();
}



回答4:


Using Apache commons-io, which is just one line of code.

FileUtils.deleteDirectory(getAlbumStorageDir(directoryName));


来源:https://stackoverflow.com/questions/13410949/delete-folder-from-internal-storage-in-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!