如何在Android上以编程方式删除文件? [英] How do I delete files programmatically on Android?

查看:141
本文介绍了如何在Android上以编程方式删除文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

目前,这些删除功能都没有实际删除文件。我的AndroidManifest.xml中也有这个:

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


推荐答案

为什么不用以下代码测试:

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.

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

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

然后尝试删除该文件。

这篇关于如何在Android上以编程方式删除文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆