从SD卡中删除非空文件夹

时间:2011-05-07 07:00:42

标签: android

我正在尝试让我的应用程序在启动时删除sdcard(带子文件夹)上的文件夹,但我不明白如何设置要删除的路径。

我创建了一个简单的Activity来删除这个文件夹,如下所示:

package org.android.test;    
import java.io.File;    
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;

public class DelSD extends Activity {

File dir = new File(android.os.Environment
        .getExternalStorageDirectory().getPath(),
        "/TEST");

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);        
    }

    void DeleteRecursive(File dir)
    {
        Log.d("DeleteRecursive", "DELETEPREVIOUS TOP" + dir.getPath());
        if (dir.isDirectory())
        {
            String[] children = dir.list();
            for (int i = 0; i < children.length; i++) 
            {
               File temp =  new File(dir, children[i]);
               if(temp.isDirectory())
               {
                   Log.d("DeleteRecursive", "Recursive Call" + temp.getPath());
                   DeleteRecursive(temp);
               }
               else
               {
                   Log.d("DeleteRecursive", "Delete File" + temp.getPath());
                   boolean b = temp.delete();
                   if(b == false)
                   {
                       Log.d("DeleteRecursive", "DELETE FAIL");
                   }
               }
            }    
            dir.delete();
        }
    }     
}

并添加到我的清单中:

uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"
uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"

但仍然没有去。 SD卡上的我的TEST文件夹仍在那里。我在模拟器和我的设备2.2上测试了这个Activity。

我不知道如何设置我的路径被删除:

File dir = new File(android.os.Environment
            .getExternalStorageDirectory().getPath(),
            "/TEST");

因为如果我将“dir”更改为其他内容,则“void DeleteRecursive(File dir)”不会抱怨“dir”未被设置!所以这根本不起作用。任何消化?

2 个答案:

答案 0 :(得分:2)

import java.io.File;

class DeleteDir {
  public static void main(String args[]) {
    deleteDirectory(new File(args[0]));
  }

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

答案 1 :(得分:0)

试试这个:

public void DeleteFromSdCard()                          //Testing purpose only
{
    File checkFile = new File("/sdcard/TEST/");
    File[] lstFile;

    if(checkFile.exists())
    {
        lstFile = checkFile.listFiles();

        for(int i =0; i<lstFile.length;i++)
        {
            File file = lstFile[i];
            file.delete();
        }
    }
}