我正在尝试删除mp3文件。
我的代码:
String path = songsList.get(position).getData();
File fdelete = new File(path);
if (fdelete.exists()) {
if (fdelete.delete()) {
DeleteRecursive(fdelete);
Log.d(TAG, "deleted");
} else {
Log.d(TAG, "failed");
}
} else {
Log.d(TAG, "file doesn't exist");
}
当我最初删除时,它会显示“已删除”消息。但是,该文件出现并且无法播放。如果再次尝试将其删除,则会显示“文件不存在”消息。
谁能告诉我如何正确删除。
任何帮助将不胜感激。谢谢。
最后,我设法从内部存储以及SD卡中完全删除了mp3文件。
这里是代码:(可能对某人有帮助)
String[] projection = new String[]{BaseColumns._ID, MediaStore.MediaColumns.DATA};
String selection = BaseColumns._ID + " IN (" + id + ")";
try {
final Cursor cursor = context.getContentResolver().query(
MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, projection, selection,null, null);
if (cursor != null) {
// remove from the media database
context.getContentResolver().delete(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,selection, null);
// remove from storage / sdcard
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
final String name = cursor.getString(1);
try {
final File f = new File(name);
if (!f.delete()) {
Log.e(TAG, "deleteSong: " + title + " can't be deleted");
}
cursor.moveToNext();
} catch (@NonNull final SecurityException ex) {
cursor.moveToNext();
} catch (NullPointerException e) {
Log.e(TAG, "Failed to find file " + name);
}
}
cursor.close();
}
context.getContentResolver().notifyChange(Uri.parse("content://media"), null);
Toast.makeText(context, title + " deleted", Toast.LENGTH_SHORT).show();
} catch (SecurityException ignored) {
}
使用此
public static void DeleteRecursive(File fileOrDirectory) {
if (fileOrDirectory.isDirectory()) {
for (File child : fileOrDirectory.listFiles()) {
DeleteRecursive(child);
}
}
fileOrDirectory.delete();
}