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

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

解决方法:

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

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

然后尝试删除文件.

相关文章

Android性能优化——之控件的优化 前面讲了图像的优化,接下...
前言 上一篇已经讲了如何实现textView中粗字体效果,里面主要...
最近项目重构,涉及到了数据库和文件下载,发现GreenDao这个...
WebView加载页面的两种方式 一、加载网络页面 加载网络页面,...
给APP全局设置字体主要分为两个方面来介绍 一、给原生界面设...
前言 最近UI大牛出了一版新的效果图,按照IOS的效果做的,页...