如何在Android上以编程方式删除文件?

Ran*_*ens 42 java android uri file delete-file

我在4.4.2,尝试通过uri删除文件(图像).这是我的代码:

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());
      }
}
Run Code Online (Sandbox Code Playgroud)

目前,这些删除功能都没有实际删除该文件.我的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" />
Run Code Online (Sandbox Code Playgroud)

小智 89

为什么不用这段代码测试这个:

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());
    }
}
Run Code Online (Sandbox Code Playgroud)

我认为问题的一部分是你永远不会尝试删除文件,你只是继续创建一个具有方法调用的变量.

所以在你的情况下,你可以尝试:

File file = new File(uri.getPath());
file.delete();
if(file.exists()){
      file.getCanonicalFile().delete();
      if(file.exists()){
           getApplicationContext().deleteFile(file.getName());
      }
}
Run Code Online (Sandbox Code Playgroud)

但是我认为这有点过分.

您添加了一条注释,表明您使用的是外部目录而不是uri.所以你应该添加如下内容:

String root = Environment.getExternalStorageDirectory().toString();
File file = new File(root + "/images/media/2918"); 
Run Code Online (Sandbox Code Playgroud)

然后尝试删除该文件.


小智 14

试试这个吧.它对我有用.

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);
Run Code Online (Sandbox Code Playgroud)


Cod*_*ife 7

我在Nougat模拟器上测试了这段代码并且它工作正常:

在清单中添加:

<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>
Run Code Online (Sandbox Code Playgroud)

在res文件夹中创建空的xml文件夹,然后在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>
Run Code Online (Sandbox Code Playgroud)

然后将下一个片段放入您的代码中(例如片段):

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);
Run Code Online (Sandbox Code Playgroud)


Ari*_*jit 5

我看到你已经找到了答案,但是它对我不起作用。Delete 一直返回 false,所以我尝试了以下操作并且它有效(对于所选答案不起作用的其他任何人):

System.out.println(new File(path).getAbsoluteFile().delete());
Run Code Online (Sandbox Code Playgroud)

System out 显然可以忽略,为了方便确认删除,我把它放出来。