0

I want to delete all files in a particular path of sdcard. I use the below code:

private void readFile(File[] file) {
   for (int i = 0; file != null && i < file.length; i++) {
      // now i check if it is a file or filename extension 
      if (file[i].isFile() && file[i].getName().endsWith("txt")) {
         fileList.add(file[i].toString());
      } else if (file[i].isDirectory()) {// if it is a file,recursive scanning
         File[] newFileList = new File(file[i].getAbsolutePath()).listFiles();
         readFile(newFileList);
      }
   }
}

Now i set scanning path:

public void onStart(Intent intent, int startId) {
String res = "";
try {
fileList = new ArrayList<String>();
File[] files = new File(FILEPATH).listFiles();
readFile(files);
for (File file : files) {
Log.i("syso", "" + file);
FileInputStream fin = new FileInputStream(file);
int length = fin.available();
byte[] buffer = new byte[length];
fin.read(buffer);
res = EncodingUtils.getString(buffer, "UTF-8");
// System.out.println(res);
boolean isDelete = file.delete();
if (isDelete = true) {
System.out.println("Deleted successful!!");
} else {
System.out.println("Deleted fail!!");
}

I set creating and deleting file permission in SDCard

Yugandhar Babu
  • 10,311
  • 9
  • 42
  • 67
bonnie
  • 331
  • 1
  • 4
  • 17
  • did you give uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" permission in android manifest? – appukrb Dec 28 '12 at 08:53
  • Try [this][1] it might help to you. [1]: http://stackoverflow.com/questions/4943629/android-how-to-delete-a-whole-folder-and-content – Ajay S Dec 28 '12 at 08:58

1 Answers1

1

I tried your code as I needed an application which deletes some files on my sdcard. On my phone your code is working. I only recognized that you use in the following line

if (isDelete = true) {

an assingment instead of a comparison operator. Therefore, I suppose the if statement will always evaluate to true and always prints that the delete was successful even if the deletion of a file failed. I think

if (isDelete == true) {

is what you wanted to write. As you did not say anything about your specific troubles with your code, I do not know how to help you besides testing your code.

joel
  • 480
  • 1
  • 5
  • 9