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

时间:2014-07-09 17:03:06

标签: java android file uri 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());
      }
}

目前,这些删除功能都没有实际删除文件。我的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" />

6 个答案:

答案 0 :(得分:82)

为什么不用此代码对此进行测试:

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());
    }
}

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

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

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

但是我认为这有点矫枉过正。

您添加了一条注释,表明您使用的是外部目录而不是uri。所以你应该添加类似的东西:

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

然后尝试删除该文件。

答案 1 :(得分: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);

答案 2 :(得分: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>

在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>

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

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

答案 3 :(得分:4)

我看到你找到了答案,但这对我没用。删除保持返回false,所以我尝试了以下它并且它有效(对于所选择的答案不起作用的任何其他人):

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

显然可以忽略系统输出,我把它放在确认删除的方便之处。

答案 4 :(得分:1)

首先调用意图

Intent intenta = new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE);
startActivityForResult(intenta, 42);

然后调用结果

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    switch (requestCode) {
        case 42:
            if (resultCode == Activity.RESULT_OK) {
                Uri sdCardUri = data.getData();
                DocumentFile pickedDir = DocumentFile.fromTreeUri(this, sdCardUri);
                for (DocumentFile file : pickedDir.listFiles()) {
                    String pp = file.getName();
                    if(pp.equals("VLC.apk"))
                        file.delete();
                    String ppdf="";
                }
                File pathFile = new File(String.valueOf(sdCardUri));
                pathFile.delete();
            }
            break;
    }
}

答案 5 :(得分:0)

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

在我的情况下不起作用。使用以下代码已解决了该问题-

ContentResolver contentResolver = getContentResolver ();
contentResolver.delete (uriDelete,null ,null );