Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/342.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何在Android上以编程方式删除文件?_Java_Android_File_Uri_Delete File - Fatal编程技术网

Java 如何在Android上以编程方式删除文件?

Java 如何在Android上以编程方式删除文件?,java,android,file,uri,delete-file,Java,Android,File,Uri,Delete File,我在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

我在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());
      }
}
现在,这些删除函数实际上都没有删除文件。我的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" />

为什么不使用以下代码测试此功能:

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());
    }
}
我认为问题的一部分是,您从未尝试删除该文件,您只是不断创建一个具有方法调用的变量

因此,在您的情况下,您可以尝试:

File file = new File(uri.getPath());
file.delete();
if(file.exists()){
      file.getCanonicalFile().delete();
      if(file.exists()){
           getApplicationContext().deleteFile(file.getName());
      }
}
不过我觉得这有点过分了

您添加了一条注释,说明您使用的是外部目录而不是uri。因此,您应该添加以下内容:

String root = Environment.getExternalStorageDirectory().toString();
File file = new File(root + "/images/media/2918"); 

然后尝试删除该文件。

尝试此文件。它对我有用

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);

我知道你已经找到了答案,但对我来说不起作用。Delete一直返回false,因此我尝试了以下方法,并且成功了(对于选择的答案不起作用的任何其他人):


很明显,系统输出可以忽略,我把它放在这里是为了方便确认删除。

我在牛轧糖仿真器上测试了这段代码,它成功了:

在清单中添加:

<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>
先说出意图

Intent intenta = new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE);
startActivityForResult(intenta, 42);
然后调用结果

@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;
    }
}
File File=新文件(getFilePath(imageUri.getValue());
布尔b=file.delete();
在我的情况下不起作用。该问题已通过使用以下代码解决-

ContentResolver ContentResolver=getContentResolver();
contentResolver.delete(uriDelete,null,null);

我不使用getCanonicalFile(),只使用File.delete(),它在我的系统上运行良好。除非您的URI路径无效。我的路径是:/external/images/media/2918看起来对吗?。。。不是。类似于
/mnt/sdcard/your_folder/your_file.png
的东西可以。但是,最好通过
getExternalDirectory
获取存储路径。最后,权限
WRITE\u EXTERNAL\uuu…
包括
READ\u EXTERNAL\uu…
一个。谢谢,我现在可以使用它了。我想你可能在做什么。它一直在说fdelete不存在。我的文件路径是/external/images/media/2918。这看起来对吗?我认为你的解决方案在他的情况下不起作用,因为他已经按照你告诉他的那样做了。而不是
uri.getPath()
尝试我刚才在答案中实现的内容。@Saturisk他几乎按照你告诉的那样做。他的问题是他走错了路。我的解决办法会奏效的,他只是回答错了。他说他正在使用uri获取路径,但他没有。我确定了回答他的问题的答案。
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);
Intent intenta = new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE);
startActivityForResult(intenta, 42);
@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;
    }
}