How do I delete files programmatically on Android?

132,807

Solution 1

Why don't you test this with this code:

File fdelete = new File(uri.getPath());
if (fdelete.exists()) {
    if (fdelete.delete()) {
        System.out.println("file Deleted :" + uri.getPath());
    } else {
        System.out.println("file not Deleted :" + uri.getPath());
    }
}

I think part of the problem is you never try to delete the file, you just keep creating a variable that has a method call.

So in your case you could try:

File file = new File(uri.getPath());
file.delete();
if(file.exists()){
      file.getCanonicalFile().delete();
      if(file.exists()){
           getApplicationContext().deleteFile(file.getName());
      }
}

However I think that's a little overkill.

You added a comment that you are using an external directory rather than a uri. So instead you should add something like:

String root = Environment.getExternalStorageDirectory().toString();
File file = new File(root + "/images/media/2918"); 

Then try to delete the file.

Solution 2

Try this one. It is working for me.

handler.postDelayed(new Runnable() {
    @Override
    public void run() {
        // Set up the projection (we only need the ID)
        String[] projection = { MediaStore.Images.Media._ID };

        // Match on the file path
        String selection = MediaStore.Images.Media.DATA + " = ?";
        String[] selectionArgs = new String[] { imageFile.getAbsolutePath() };

        // Query for the ID of the media matching the file path
        Uri queryUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
        ContentResolver contentResolver = getActivity().getContentResolver();
        Cursor c = contentResolver.query(queryUri, projection, selection, selectionArgs, null);

        if (c != null) {
            if (c.moveToFirst()) {
                // We found the ID. Deleting the item via the content provider will also remove the file
                long id = c.getLong(c.getColumnIndexOrThrow(MediaStore.Images.Media._ID));
                Uri deleteUri = ContentUris.withAppendedId(queryUri, id);
                contentResolver.delete(deleteUri, null, null);
            } else {
                // File not found in media store DB
            }
            c.close();
        }
    }
}, 5000);

Solution 3

I tested this code on Nougat emulator and it worked:

In manifest add:

<application...

    <provider
        android:name="android.support.v4.content.FileProvider"
        android:authorities="${applicationId}.provider"
        android:exported="false"
        android:grantUriPermissions="true">
        <meta-data
            android:name="android.support.FILE_PROVIDER_PATHS"
            android:resource="@xml/provider_paths"/>
    </provider>
</application>

Create empty xml folder in res folder and past in the provider_paths.xml:

<?xml version="1.0" encoding="utf-8"?>
 <paths xmlns:android="http://schemas.android.com/apk/res/android">
   <external-path name="external_files" path="."/>
  </paths>

Then put the next snippet into your code (for instance fragment):

File photoLcl = new File(homeDirectory + "/" + fileNameLcl);
Uri imageUriLcl = FileProvider.getUriForFile(getActivity(), 
  getActivity().getApplicationContext().getPackageName() +
    ".provider", photoLcl);
ContentResolver contentResolver = getActivity().getContentResolver();
contentResolver.delete(imageUriLcl, null, null);

Solution 4

I see you've found your answer, however it didn't work for me. Delete kept returning false, so I tried the following and it worked (For anybody else for whom the chosen answer didn't work):

System.out.println(new File(path).getAbsoluteFile().delete());

The System out can be ignored obviously, I put it for convenience of confirming the deletion.

Solution 5

File file=new File(getFilePath(imageUri.getValue()));
boolean b= file.delete();

not working in my case. The issue has been resolved by using below code-

ContentResolver contentResolver = getContentResolver ();
contentResolver.delete (uriDelete,null ,null );
Share:
132,807
Randall Stephens
Author by

Randall Stephens

iPhone Developer

Updated on November 24, 2021

Comments

  • Randall Stephens
    Randall Stephens over 2 years

    I'm on 4.4.2, trying to delete a file (image) via uri. Here's my code:

    File file = new File(uri.getPath());
    boolean deleted = file.delete();
    if(!deleted){
          boolean deleted2 = file.getCanonicalFile().delete();
          if(!deleted2){
               boolean deleted3 = getApplicationContext().deleteFile(file.getName());
          }
    }
    

    Right now, none of these delete functions is actually deleting the file. I also have this in my AndroidManifest.xml:

    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.WRITE_INTERNAL_STORAGE" />
    
  • Randall Stephens
    Randall Stephens almost 10 years
    I think you might be onto something. it keeps saying that fdelete doesn't exist. My file path is /external/images/media/2918. Does that look right?
  • migos
    migos almost 10 years
    i don't think your solution will work in his case because he is already doing it like you told him to do.
  • Shawnic Hedgehog
    Shawnic Hedgehog almost 10 years
    Instead of uri.getPath() try what I just implemented into the answer.
  • migos
    migos almost 10 years
    @Saturisk he is nearly doing the same like you told to do. his problem is that he has the wrong path.
  • Shawnic Hedgehog
    Shawnic Hedgehog almost 10 years
    My solution will work, he just had his answer wrong. He said he was using a uri to get the path, when he wasn't. I fixed my answer to answer his question.
  • Randall Stephens
    Randall Stephens almost 10 years
    That's correct. I'm just fixing my application and testing it and then I'll be upvoting and marking things as correct.
  • Dhara Patel
    Dhara Patel over 6 years
    using this code image deleted successfully but there is blank black image remains in gallery is there any solution for this problem ?
  • user207421
    user207421 almost 6 years
    Eh? He has not one but two lines of code that 'try to delete the file'.
  • Allinone51
    Allinone51 over 3 years
    "I think part of the problem is you never try to delete the file, you just keep creating a variable that has a method call." ? What he's doing in his question is correct. The File.delete() function does return a boolean value to inform you if the delete was a success or not. Nothing wrong with that...
  • EAS
    EAS over 2 years
    Code is not working in android 11
  • Ezequiel Adrian
    Ezequiel Adrian about 2 years
    OP is asking how to delete files, your case is about Scoped Storage, which is substantially different.
  • zeleven
    zeleven almost 2 years
    How can you delete a file by using getApplicationContext().deleteFile(file.getName());? The deleteFile() method can only passed in a name which without the leading path, so how can you delete the file? It does nothing actually, after delete my file is exist still, and I can open the file.