Java 如何在 Android 上以编程方式删除文件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24659704/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I delete files programmatically on Android?
提问by Randall Stephens
I'm on 4.4.2, trying to delete a file (image) via uri. Here's my code:
我在 4.4.2 上,尝试通过 uri 删除文件(图像)。这是我的代码:
File file = new File(uri.getPath());
boolean deleted = file.delete();
if(!deleted){
boolean deleted2 = file.getCanonicalFile().delete();
if(!deleted2){
boolean deleted3 = getApplicationContext().deleteFile(file.getName());
}
}
Right now, none of these delete functions is actually deleting the file. I also have this in my AndroidManifest.xml:
现在,这些删除功能都没有真正删除文件。我的 AndroidManifest.xml 中也有这个:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_INTERNAL_STORAGE" />
采纳答案by Shawnic Hedgehog
Why don't you test this with this code:
你为什么不用这个代码测试这个:
File fdelete = new File(uri.getPath());
if (fdelete.exists()) {
if (fdelete.delete()) {
System.out.println("file Deleted :" + uri.getPath());
} else {
System.out.println("file not Deleted :" + uri.getPath());
}
}
I think part of the problem is you never try to delete the file, you just keep creating a variable that has a method call.
我认为问题的一部分是你从不尝试删除文件,你只是不断创建一个具有方法调用的变量。
So in your case you could try:
因此,在您的情况下,您可以尝试:
File file = new File(uri.getPath());
file.delete();
if(file.exists()){
file.getCanonicalFile().delete();
if(file.exists()){
getApplicationContext().deleteFile(file.getName());
}
}
However I think that's a little overkill.
不过我觉得这有点矫枉过正。
You added a comment that you are using an external directory rather than a uri. So instead you should add something like:
您添加了一条评论,说明您使用的是外部目录而不是 uri。因此,您应该添加如下内容:
String root = Environment.getExternalStorageDirectory().toString();
File file = new File(root + "/images/media/2918");
Then try to delete the file.
然后尝试删除该文件。
回答by Krishna
Try this one. It is working for me.
试试这个。它对我有用。
handler.postDelayed(new Runnable() {
@Override
public void run() {
// Set up the projection (we only need the ID)
String[] projection = { MediaStore.Images.Media._ID };
// Match on the file path
String selection = MediaStore.Images.Media.DATA + " = ?";
String[] selectionArgs = new String[] { imageFile.getAbsolutePath() };
// Query for the ID of the media matching the file path
Uri queryUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
ContentResolver contentResolver = getActivity().getContentResolver();
Cursor c = contentResolver.query(queryUri, projection, selection, selectionArgs, null);
if (c != null) {
if (c.moveToFirst()) {
// We found the ID. Deleting the item via the content provider will also remove the file
long id = c.getLong(c.getColumnIndexOrThrow(MediaStore.Images.Media._ID));
Uri deleteUri = ContentUris.withAppendedId(queryUri, id);
contentResolver.delete(deleteUri, null, null);
} else {
// File not found in media store DB
}
c.close();
}
}
}, 5000);
回答by Arijit
I see you've found your answer, however it didn't work for me. Delete kept returning false, so I tried the following and it worked (For anybody else for whom the chosen answer didn't work):
我看到你已经找到了答案,但是它对我不起作用。Delete 一直返回 false,所以我尝试了以下操作并且它起作用了(对于所选答案不起作用的其他人):
System.out.println(new File(path).getAbsoluteFile().delete());
The System out can be ignored obviously, I put it for convenience of confirming the deletion.
System out 显然可以忽略,为了方便确认删除,我把它放出来。
回答by CodeToLife
I tested this code on Nougat emulator and it worked:
我在 Nougat 模拟器上测试了这段代码,它有效:
In manifest add:
在清单中添加:
<application...
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="${applicationId}.provider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/provider_paths"/>
</provider>
</application>
Create empty xml folder in res folder and past in the provider_paths.xml:
在 res 文件夹中创建空的 xml 文件夹并在 provider_paths.xml 中过去:
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-path name="external_files" path="."/>
</paths>
Then put the next snippet into your code (for instance fragment):
然后将下一个片段放入您的代码中(例如片段):
File photoLcl = new File(homeDirectory + "/" + fileNameLcl);
Uri imageUriLcl = FileProvider.getUriForFile(getActivity(),
getActivity().getApplicationContext().getPackageName() +
".provider", photoLcl);
ContentResolver contentResolver = getActivity().getContentResolver();
contentResolver.delete(imageUriLcl, null, null);
回答by Alain Brizuela
first call the intent
首先调用意图
Intent intenta = new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE);
startActivityForResult(intenta, 42);
then call the result
然后调用结果
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case 42:
if (resultCode == Activity.RESULT_OK) {
Uri sdCardUri = data.getData();
DocumentFile pickedDir = DocumentFile.fromTreeUri(this, sdCardUri);
for (DocumentFile file : pickedDir.listFiles()) {
String pp = file.getName();
if(pp.equals("VLC.apk"))
file.delete();
String ppdf="";
}
File pathFile = new File(String.valueOf(sdCardUri));
pathFile.delete();
}
break;
}
}
回答by Vishakha
File file=new File(getFilePath(imageUri.getValue())); boolean b= file.delete();
文件文件=新文件(getFilePath(imageUri.getValue()));boolean b= file.delete();
not working in my case. The issue has been resolved by using below code-
在我的情况下不起作用。该问题已通过使用以下代码解决-
ContentResolver contentResolver = getContentResolver (); contentResolver.delete (uriDelete,null ,null );
ContentResolver contentResolver = getContentResolver(); contentResolver.delete (uriDelete,null,null);