[英]Delete Image From Storage
I want to delete an image file from storage but it returns false.我想从存储中删除一个图像文件,但它返回 false。
I created in my app, I can delete it but when I reinstall my app I can show it but I can't delete it我在我的应用程序中创建,我可以删除它,但是当我重新安装我的应用程序时,我可以显示它,但我无法删除它
Here's my code:这是我的代码:
if (ContextCompat.checkSelfPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
File file = new File(cartPostalDbs.get(position).getFilePath());
boolean deleted = file.delete();
if (deleted) {
cartPostalDbs.remove(mPos);
notifyDataSetChanged();
} else {
Toast.makeText(context, "Can Not Delete File", Toast.LENGTH_SHORT).show();
}
}
Here's my file path这是我的文件路径
/storage/emulated/0/Pictures/yadim/1/1558.jpg
and I check PERMISSION and use this permission:我检查权限并使用此权限:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_INTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_INTERNAL_STORAGE" />
That's what you need, it works in multiple cases:这就是您所需要的,它适用于多种情况:
•If you want to delete a directory ( folder ) •If the file/directory that you want to delete doesn't exist •如果要删除目录(文件夹)•如果要删除的文件/目录不存在
here is the code:这是代码:
public void deleteFile(String path) {
File file = new File(path);
if (!file.exists()) return;
if (file.isFile()) {
file.delete();
return;
}
File[] fileArr = file.listFiles();
if (fileArr != null) {
for (File subFile : fileArr) {
if (subFile.isDirectory()) {
deleteFile(subFile.getAbsolutePath());
}
if (subFile.isFile()) {
subFile.delete();
}
}
}
file.delete();
}
usage:用法:
deleteFile(cartPostalDbs.get(position).getFilePath());
your final code should look like this:您的最终代码应如下所示:
if (ContextCompat.checkSelfPermission(context,
Manifest.permission.WRITE_EXTERNAL_STORAGE) ==
PackageManager.PERMISSION_GRANTED) {
try {
deleteFile(cartPostalDbs.get(position).getFilePath());
boolean deleted = true;
} catch ( Exception e ) { boolean deleted = false; }
if (deleted) {
cartPostalDbs.remove(mPos);
notifyDataSetChanged();
} else {
Toast.makeText(context, "Can Not Delete File", Toast.LENGTH_SHORT).show();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.