无法删除文件(.delete()返回false)

时间:2018-10-19 14:41:49

标签: android android-permissions android-file

我正在尝试从目录中删除图像,但是当我使用该方法时,它返回false

Locale

我一直在收集其他帖子的示例,但没有一个适合我

清单:

public void deleteImage() {

    String file_path = Environment.getExternalStorageDirectory() + "/Angular/JPEG_20181010_282_9_320446411.jpg";

    //Result Path: /storage/emulated/0/Angular/JPEG_20181010_282_9_320446411.jpg

    File fdelete = new File(file_path); 
    if (fdelete.exists()) {
        if (fdelete.delete()) { //This return false
            Log.e("-->", "file Deleted :" + file_path );
        } else {
            Log.e("-->", "file not Deleted :" + file_path );
        }
    }
}

1 个答案:

答案 0 :(得分:0)

将逻辑和方法更改为:

public void deleteImage() {

    String file_path = Environment.getExternalStorageDirectory() + "/Angular/JPEG_20181010_282_9_320446411.jpg";

    //Result Path: /storage/emulated/0/Angular/JPEG_20181010_282_9_320446411.jpg

    File fdelete = new File(file_path); 
    if (fdelete.exists()) {
            fdelete.delete() // delete the file here
            Log.e("-->", "Success, file Deleted :" + file_path);
        } else {
            Log.e("-->", "file not Deleted :" + file_path);
        }
}

exists()将检查它是否存在,不需要额外的条件。

最好在try-catch内添加代码,以便将来捕获所有情况。 (没有权限或任何错误)