简体   繁体   English

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

[英]How do I delete files programmatically on Android?

I'm on 4.4.2, trying to delete a file (image) via uri.我在 4.4.2 上,尝试通过 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:我的 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" />

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.您添加了一条评论,说明您使用的是外部目录而不是 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.然后尝试删除该文件。

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

I tested this code on Nougat emulator and it worked:我在 Nougat 模拟器上测试了这段代码,它有效:

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

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

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): Delete 一直返回 false,所以我尝试了以下操作并且它起作用了(对于所​​选答案不起作用的其他人):

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

The System out can be ignored obviously, I put it for convenience of confirming the deletion. System out 显然可以忽略,为了方便确认删除,我把它放出来。

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

first call the intent首先调用意图

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

then call the result然后调用结果

@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;
    }
}

You can delete a file by using delete() method.您可以使用delete()方法删除文件。

For that first you need to create a File reference in your code by specifying the path of the file as argument, then call delete() method to delete the file.为此,您首先需要通过指定文件路径作为参数在代码中创建文件引用,然后调用delete()方法删除文件。

String path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/video1.mp4";
new File(path).delete();

在 kotlin 中使用 uri 删除图像:

val file = File(uri.path).delete()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在Android中以编程方式删除图片? - How can I delete picture programmatically in Android? 我如何以编程方式在 Android 中 ping 一个网站 - How do I programmatically ping a website in Android 我如何以编程方式锁定手机android - How do i lock phone programmatically android 如何在Android中以编程方式反编译dex文件? - How can I programmatically decompile dex files within Android? 如何在 Android 中以编程方式解压缩文件? - How to unzip files programmatically in Android? 如何以编程方式删除 android 工作室中的搜索栏 - How to programmatically delete a seekbar in android studio 我如何使用 java 代码以编程方式在 android 上运行 cmd 命令 - how do i run cmd command on android programmatically with java code 如何在 Android 上以编程方式启用/禁用热点或网络共享模式? - How do I enable/disable hotspot or tethering mode programmatically on Android? 是否可以以编程方式从android上的照片/视频目录中删除所有文件? - is it possible to delete all files from photo/video directory on android programmatically? 如何在Android中以编程方式交换视图控件? - How do I programmatically swap out a view control in Android?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM