Android的删除目录不工作 [英] Android Delete Directory Not Working

查看:105
本文介绍了Android的删除目录不工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想Ø删除整个目录。我已搜查,我使用这个 code,我能够删除一切都在目录中,但目录仍然存在。这里是确切的code我有以防万一,我失去了一些东西。

I am trying o delete an entire directory. I have searched and I am using this code and I am able to delete everything in the directory, but the directory still remains. Here is the exact code I have just in case I am missing something.

public boolean DeletePoint(String JobName, String PointName){
    //Delete actual contents and file
    File folder = new File(rootSaveFolder "/" + PointName+"/");
    boolean returnBool = false; 
    try{
        returnBool = deleteDirectory(folder);
        folder.delete();
    } catch (SecurityException e){
        e.printStackTrace();
    }   
}

static public boolean deleteDirectory(File path) {
    if( path.exists() ) {
      File[] files = path.listFiles();
      if (files == null) {
          return true;
      }
      for(int i=0; i<files.length; i++) {
         if(files[i].isDirectory()) {
           deleteDirectory(files[i]);
         }
         else {
           files[i].delete();
         }
      }
    }
    return(path.delete());
  } 

因为我删除文件的字符串是:到/ mnt / SD卡/测试/ GG /

The string for the file I am deleting is: /mnt/sdcard/test/gg/

我与尝试过了最后的'/',而且也不能工作。

I have tried it with out the final '/' and that didn't work either.

推荐答案

下面是你的问题;

您递归是差不多吧...
这里的问题。

Your recursion is almost right... Here's the problem.

如果文件[i]为一个目录,(你理所​​当然地去它来清除一切)
然而,一旦在文件中[I]一切被删除,你实际上并没有删除文件[I]本身。

If files[i] is a directory, (you rightfully go to clear everything in it) However, once "everything" in files[i] is deleted, you do not actually delete files[i] itself.

所以递归是不完整的;
你需要做的是去除
其他
在fo​​rloop内。

So the recursion is incomplete; What you need to do is remove the "else" within the forloop.

在文件[I]这是一个目录,将在它所有的东西清理干净了这种方式已被删除。你只是离开它。

That way when files[i] which is a directory, will be cleaned up after all things in it have been removed. You were just leaving it.

要更具体地:

public void deleteFile(String uri)
{
     File currentFile = new File(uri);
     File files[] = currentFile.listFiles();
     for (int i = 0; i < files.length; i++)
     {
          if (files[i].isDirectorty())
          {
              deleteFiles(files[i].toString());
          }
          //no else, or you'll never get rid of this folder!
          files[i].delete();
     }
}

这篇关于Android的删除目录不工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆