Android中的file.delete()会留下一个不可读的小文件

时间:2017-06-04 22:11:54

标签: java android image file

我正在尝试从我的图库中删除图片。我使用的是从这里得到的代码:
android : deleting an image

这似乎对一些人有用,但遗憾的是不适合我。如果我运行它,一个小的,不可读的文件仍然存在。我在Android 4.1.2上。

以下是代码:

public void deleteImage(File fdelete) {
    //String file_dj_path = Environment.getExternalStorageDirectory() + "/ECP_Screenshots/abc.jpg";
    //File fdelete = new File(file_dj_path);
    if (fdelete.exists()) {
        if (fdelete.delete()) {
            Log.e("-->", "file Deleted :" + fdelete);
            callBroadCast();
        } else {
            Log.e("-->", "file not Deleted :" + fdelete);
        }
    }
}

public void callBroadCast() {
    if (Build.VERSION.SDK_INT >= 14) {
        Log.e("-->", " >= 14");
        MediaScannerConnection.scanFile(this, new String[]{Environment.getExternalStorageDirectory().toString()}, null, new MediaScannerConnection.OnScanCompletedListener() {
            /*
             *   (non-Javadoc)
             * @see android.media.MediaScannerConnection.OnScanCompletedListener#onScanCompleted(java.lang.String, android.net.Uri)
             */
            public void onScanCompleted(String path, Uri uri) {
                Log.e("ExternalStorage", "Scanned " + path + ":");
                Log.e("ExternalStorage", "-> uri=" + uri);
            }
        });
    } else {
        Log.e("-->", " < 14");
        sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED,
                Uri.parse("file://" + Environment.getExternalStorageDirectory())));
    }
}

1 个答案:

答案 0 :(得分:0)

如果通过

  

小的不可读文件

你的意思是零,你可以这样做:

long fileSize = fdelete.length();
if (fdelete.exists() || fileSize==0){
    fdelete.delete();
}

然后做

    if (fdelete.delete()) {
        Log.e("-->", "file Deleted :" + fdelete);
        callBroadCast();
    } else {
        Log.e("-->", "file not Deleted :" + fdelete);
    }