9

I have a method to download a image from url and save it in a folder at Internal storage

 public void saveDynamicImage(String url,String fileName, String folderName) {

    InputStream iStream;

    BufferedInputStream buffInputStream;
    ByteArrayBuffer byteArray = null;

    try {
        HttpGet httpGet = new HttpGet(url);
        HttpClient httpClient = new DefaultHttpClient();
        HttpResponse httpResponse = httpClient.execute(httpGet);
        iStream = httpResponse.getEntity().getContent();

        buffInputStream = new BufferedInputStream(iStream, 8 * 1024);
        byteArray = new ByteArrayBuffer(50);
        int current = 0;
        while ((current = buffInputStream.read()) != -1) {
            byteArray.append((byte) current);
        } 

    } catch (ClientProtocolException e1) {
    } catch (IOException e1) {
    }

    File dynamicImageDir = context.getDir(AppConstants.DYNAMIC_IMAGE, Context.MODE_PRIVATE);
    File appNamefileDir = new File(dynamicImageDir, BaseActivity.appDataStore.getAppName());
    appNamefileDir.mkdirs();
    File controlNameDir = new File(appNamefileDir, folderName);
    controlNameDir.mkdirs();
    File file = new File(controlNameDir, fileName);

    try {
        FileOutputStream outputStream = new FileOutputStream(file);
        outputStream.write(byteArray.toByteArray());
        outputStream.close();
        System.out.println("DynamicImage saving over!..");
    } catch (FileNotFoundException e) {
    } catch (IOException e) {
    }
}

i want to delete the whole directory at a point of time. My method to delete entire directory is

public void deleteDynamicImage() throws NullPointerException,FileNotFoundException {
    File rootDirectory = context.getDir(AppConstants.DYNAMIC_IMAGE, Context.MODE_WORLD_WRITEABLE);
    boolean status = rootDirectory.delete();
    Log.e("", "delete : "+status);

}

i am getting the status as 'false'. files are created and working fine. only problem in deletion. Is there any thing I am missing?

tshepang
  • 12,111
  • 21
  • 91
  • 136
Arundas K V
  • 801
  • 2
  • 14
  • 28

4 Answers4

28

Is your file a directory?

If it's, you need to delete file in this folder first
this code is work well

public void deleteDirectory(File file) {
    if( file.exists() ) {
        if (file.isDirectory()) {
            File[] files = file.listFiles();
            for(int i=0; i<files.length; i++) {
                if(files[i].isDirectory()) {
                    deleteDirectory(files[i]);
                }
                else {
                    files[i].delete();
                }
            }
        }
            file.delete();
    }
}
henry4343
  • 3,871
  • 5
  • 22
  • 30
  • Thank you very much. This method works for me. .. very good implementation.. Thank you very much – Arundas K V Feb 13 '14 at 10:06
  • Thanks for the working method! Things like this bother me about Android development, there are so many quirks in the SDK where things should work but dont. You would think that if File object supports directories, then all methods should support both files & dirs - clear evidence of poor class design. – AlexVPerl Jun 26 '15 at 19:05
  • Works correctly but not is slow ? if you activate to 200 entries every time ? –  Oct 14 '15 at 21:12
6

To delete Directory use this:

public void DeleteRecursive(File fileOrDirectory) {
    if (fileOrDirectory.isDirectory()) for (File child : fileOrDirectory.listFiles())
    DeleteRecursive(child);
    fileOrDirectory.delete();
}
Vikas Rathod
  • 374
  • 2
  • 14
  • thanks for your answer, but i am accepting the first received answer as the Accepted answer. thank you very much – Arundas K V Feb 13 '14 at 10:10
  • No problem :) which code you are using for ur implementation, just for curiosity :P – Vikas Rathod Feb 13 '14 at 10:14
  • both code works well, but the code by 'henry4343' having a check for existence of file/directory. I have various sub folders and nested files. so i am using the answer from that user. Thank you..:) – Arundas K V Feb 13 '14 at 10:29
  • Works fine, and seems that is fast –  Oct 14 '15 at 21:15
4

How to delete File in Android:

public void deleteFile(String filePath){
    if(filePath.startsWith("content://")){
        ContentResolver contentResolver = getActivity().getContentResolver();
        contentResolver.delete(Uri.parse(filePath), null, null);
    }else {
        File file = new File(filePath);
        if(file.exists()) {
            if (file.delete()) {
                Log.e(TAG, "File deleted.");
            }else {
                Log.e(TAG, "Failed to delete file!");
            }
        }else {
            Log.e(TAG, "File not exist!"); 
        }
    }
}

Important Note: if you get file path from Uri [Don't use Uri.toString()] as it will return file path in file:/// format, in this case [new File(filePath)] will not work. So to get file path always use Uri.getPath().

Ayman Al-Absi
  • 2,630
  • 24
  • 22
3

You are trying to delete a directory. File.delete() works on directory only if this is empty

Blackbelt
  • 156,034
  • 29
  • 297
  • 305