无法从存储中删除文件

时间:2019-10-11 07:26:51

标签: android file storage

我正在尝试从手机存储中删除文件,但该文件始终返回false。我已经尝试了堆栈上给出的大多数方法,但是没有任何效果。

 final File file = new File(path);
        if (path != null) {
            AlertDialog alertDialog = new AlertDialog
                    .Builder(getContext()).setTitle("Delete")
                    .setMessage("Are you sure you want to delete this video?")
                    .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                               boolean fileDeleted =  file.delete();
                                Toast.makeText(getContext(), String.valueOf(fileDeleted), Toast.LENGTH_SHORT).show();
                            mAdapter.notifyDataSetChanged();
                        }
                    })
                    .setNegativeButton(android.R.string.cancel, null)
                    .setIcon(android.R.drawable.ic_dialog_alert)
                    .show();
        }

3 个答案:

答案 0 :(得分:0)

您可以尝试以下代码:

public class FileUtils {

    public static boolean deleteFile(File file, Context context) {
        if (file == null || !file.exists()) return true;
        file.delete();
        if (file.exists()) {
            try {
                file.getCanonicalFile().delete();
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (file.exists()) context.deleteFile(file.getName());
        }
        return !file.exists();
    }
}

答案 1 :(得分:0)

告诉我要传递到文件中的文件路径,如果将文件写入SD卡,则无法删除它,因为 从Android 4.4开始,应用程序无法再写入Micro SD卡。

答案 2 :(得分:0)

这是我尝试许多方法后使用的代码。

private static boolean delete(final Context context, final File file) {
    final String where = MediaStore.MediaColumns.DATA + "=?";
    final String[] selectionArgs = new String[] {
            file.getAbsolutePath()
    };
    final ContentResolver contentResolver = context.getContentResolver();
    final Uri filesUri = MediaStore.Files.getContentUri("external");

    contentResolver.delete(filesUri, where, selectionArgs);

    if (file.exists()) {

        contentResolver.delete(filesUri, where, selectionArgs);
    }
    return !file.exists();
}