首页 > 解决方案 > 无法从存储中删除文件

问题描述

我正在尝试从手机存储中删除一个文件,但它总是返回 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();
        }

标签: androidfilestorage

解决方案


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

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

推荐阅读