2011-05-07 76 views
2

我想讓我的應用程序刪除SD卡上的文件夾(與子文件夾)開始,但我不明白如何設置要刪除的路徑。從SD卡刪除一個非空文件夾

我創建了一個簡單的活動刪除此文件夾這樣的:

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"); 

,因爲如果我改變「目錄」別的東西「空缺DeleteRecursive(文件目錄)」不抱怨「:

我不明白我應該如何設置我的路徑與被刪除目錄「未設置!所以這根本不起作用。任何消化?

+0

'新文件(android.os.Environment.getExternalStorageDirectory()的getPath(), 「TEST」);'爲我工作。你確定你在調用'DeleteRecursive'嗎?在您的代碼中找不到它... – FrVaBe 2011-05-07 20:52:11

+0

[刪除SD卡上的文件夾]可能的重複(http://stackoverflow.com/questions/5701586/delete-a-folder-on-sd-card) – 2012-04-03 10:33:26

回答

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(); 
     } 
    } 
} 
+0

沒有工作,沒有一個。 :( – bernabap 2011-05-07 18:04:03

+0

首先這可能不是SD卡的路徑,第二個'file.delete();'當'file'對象是非空的目錄時不會刪除任何東西。 – 2011-12-22 21:34:25

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()); 
    } 
}