How do I delete files programmatically on Android?

2019-01-08 19:57发布

问题:

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" />

回答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.



回答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.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(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, id);
                                    contentResolver.delete(deleteUri, null, null);
                                } else {
                                    // File not found in media store DB
                                }
                                c.close();
                            }
                        }, 5000);


回答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);


回答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.