【发布时间】:2018-05-03 09:56:32
【问题描述】:
我已阅读此论坛中的所有主题,但没有任何内容适合我。我有文件路径的arraylist,我需要删除其中的一些。在我的代码中,我尝试使用:
File file = new File(filesPath.get(0));
file.delete();
if (file.exists()) {
try {
file.getCanonicalFile().delete();
} catch (IOException e) {
e.printStackTrace();
}
if (file.exists()) {
file.getAbsoluteFile().delete();
}
}
Log.e("MyLogs", file.exists() ? "true" : "false");
我从 MediaStore 获得的文件路径,它看起来像“/storage/extSdCard/mmm/bensound-summer.mp3”。我可以毫无问题地阅读此路径,但无法删除它。这是我获取字符串数组的代码:
ArrayList<String> filesPath = new ArrayList<>();
Uri contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
String[] projection = {MediaStore.Images.Media.DATA};
try {
Cursor cursor = context.getContentResolver().query(
contentUri,
projection,
MediaStore.Audio.Media.IS_MUSIC + " != 0",
null,
null);
if (cursor != null && cursor.moveToFirst() && cursor.getCount() > 0) {
do {
String path = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.DATA));
File file = new File(path);
if (file.exists())
filesPath.add(path);
} while (cursor.moveToNext());
return filesPath;
} else {
return null;
}
} catch (Exception ex) {
ex.printStackTrace();
return null;
}
当然我添加了清单的权限:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
来自this link,我为自己获取了一些代码,但它并没有帮助我解决我的问题,这就是我在这里写问题的原因。
编辑:
刚刚找到重点:我无法从 sdcard(可移动)中删除文件!!!从decive的存储中删除所有内容都没有任何问题。
编辑 2:
try {
long id = -1;
Cursor cursor = context.getContentResolver().query(
MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
new String[] { MediaStore.Audio.Media._ID },
MediaStore.Audio.Media.DATA + "=?",
new String[] { file.getAbsolutePath() },
null);
if (cursor != null && cursor.moveToFirst() && cursor.getCount() > 0) {
id = cursor.getLong(cursor.getColumnIndex(MediaStore.MediaColumns._ID));
cursor.close();
Uri uri = Uri.withAppendedPath(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, String.valueOf(id));
DocumentFile documentFile = DocumentFile.fromSingleUri(context, uri);
if (documentFile.delete()) {
Uri mediaContentUri = ContentUris.withAppendedId(
MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
id
);
context.getContentResolver().delete(mediaContentUri, null, null);
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
我得到一个异常错误:
Failed to delete document
java.lang.UnsupportedOperationException: Unsupported call: android:deleteDocument
错误指向documentFile.delete()
行【问题讨论】:
标签: android file delete-file