java - 如何使用文件路径从存储中删除文件?
问题描述
我正在开发一个应用程序,该应用程序列出了共享内部存储和可移动 SD 卡中的所有音频文件。现在,如果用户想要删除特定文件,它将从共享内部存储或可移动 SD 卡中删除。
我面临的问题是 file.delete 不起作用,我使用 mediastore 来获取所有音频文件。
这些是我从媒体商店获得的音频文件路径。
这是来自内部共享存储。
/storage/emulated/0/Music/Guitar1.mp3
这是来自可移动微型 SD 卡。
/storage/BBF8-A8D3/Guitar1.mp3
得到这些路径后
File deleteFile = new File(s.getFilepath());
boolean delete = deleteFile.delete();
删除给出false
的删除文件没有被删除。
现在我已经尝试过了,
File deleteFile = new File(s.getFilepath());
if(deleteFile.exists()) {
boolean catchdelete = deleteFile.delete();}
现在从路径创建文件后,如果条件失败,删除文件不存在。
那么为什么新创建的文件不存在(文件不是目录)是否需要文件输入流。
我的主要问题是通过应用程序从存储中删除文件。
这是我检索音频文件路径的方法
public ArrayList<String> getAudiosPath(Activity activity, Context context) {
// Uri uri;
listOfAllAudios = new ArrayList<String>();
Cursor cursor;
final String[] columns = {MediaStore.Audio.Media.DATA, MediaStore.Audio.Media._ID};
final String orderBy = MediaStore.Audio.Media._ID;
//Stores all the audio from the gallery in Cursor
cursor = getContentResolver().query(
MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, columns, null,
null, orderBy);
//Total number of audios
int count = cursor.getCount();
//Create an array to store path to all the audios
String[] arrPath = new String[count];
for (int i = 0; i < count; i++) {
cursor.moveToPosition(i);
int dataColumnIndex = cursor.getColumnIndex(MediaStore.Audio.Media.DATA);
//Store the path of the audio
arrPath[i] = cursor.getString(dataColumnIndex);
Bitmap b = ((BitmapDrawable) ResourcesCompat.getDrawable(context.getResources(), R.drawable.headphone512, null)).getBitmap();
bitmap.add(b);
Log.i("PATH", arrPath[i]);
listOfAllAudios.add(arrPath[i]);
}
// count_paths=listOfAllAudios.size();
return listOfAllAudios;
}
现在我已经应用了 Apache Commons IO File Utils
File deleteFile = new File(s.getFilepath());
// boolean delete = deleteFile.delete();
try {
FileUtils.forceDelete(FileUtils.getFile(s.getFilepath()));
}
catch (IOException e) {
e.printStackTrace();
}
此 Apache Commons 文件实用程序确实删除了该文件,但问题是再次打开应用程序时,我看到文件大小为 0 KB 的文件路径。
在下载导航抽屉中
当在导航抽屉中时,我访问 TA-1032-> 音乐-> 空(不存在文件)(没有文件意味着文件被删除)
但是在导航抽屉中,我访问音频-> 未知-> 音乐-> Guitar.mp3(文件存在,但文件大小为 0 且无法播放)
所以这是获取文件路径的一些方法。
解决方案
这件作品可能会奏效。
Files.deleteIfExists(Paths.get("C:\\Users\\Mayank\\Desktop\\
445.mp3"));
推荐阅读
- javascript - Cypress React,找不到安装组件的根元素
- python - 在 for 循环中附加带有新键和值的字典
- microsoft-graph-api - 使用 MSAL4j 获取令牌时,在元数据文档问题中找不到认证和 WsTrust 端点 - MSgraph API
- python - 如何避免电报 API 中的 PeerFloodError
- arrays - MongoDB中每年和每月的聚合
- javascript - WkWebView - 图片未加载(目标 C)
- c# - Math.Max 处理三个可为空的值
- android - Recyclerview with Tablelayout On row click listner not working in android
- java - 卡夫卡处理器上下文 - 调度方法不起作用
- python - 为什么在 pyodide wasm 中运行 pandas 会导致内存错误?