如何仅使用 Uri 从外部存储 android studio 中删除文件

How to delete a file from external storage android studio, using only Uri

所以我看了看其他人的例子并实现了这个。

 File delete= new File(uri.getPath());
    if(delete.exists()){
        Log.d("Delete", "File Exists");
        if(delete.delete()){
            Log.d("Deleted", ""+uri);
        }
        else{
            Log.d("Unable to delete", ""+uri);
        }
    }
    else{
        Log.d("Delete", "File is not found");
    }

现在唯一的问题是我得到的路径名是"content://downloads/all_downloads/644",根据我打印的logcat,找不到这个文件。注意:此文件确实存在,我使用相同的 uri 实际播放视频。谢谢您的帮助。编辑:好的,这就是我获得 URI 的方式。

BroadcastReceiver onComplete = new BroadcastReceiver() {

    public void onReceive(Context ctxt, Intent intent) {
        Log.d("REFERENCE", "E"+"Entering Broadcast");
        long referenceId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1);
        uri=( manager.getUriForDownloadedFile(referenceId));
    }
};

现在我非常感谢下面给出的建议,但即使阅读了文档,我仍然卡住了。假设我不能使用 Uri 删除,有没有办法将我的 uri 转换成有用的东西。我不想手动输入文件所在位置的地址。

@这是我的全部代码...

public class缓存器{

private DownloadManager manager;
private Uri uri;

public Cacher(String urlIn , Context context){

    Log.d("REFERENCE", "A1- casher");
    manager= (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
    Log.d("REFERENCE", "A");
    Uri temp=Uri.parse(urlIn);
    Log.d("REFERENCE", "B");
    DownloadManager.Request request= new DownloadManager.Request(temp);
    //
    request.setNotificationVisibility(Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
    Long reference=manager.enqueue(request);
    // Toast.makeText(this,""+reference,Toast.LENGTH_LONG);
    Log.d("REFERENCE", "C"+"Downloading video");
    Log.d("REFERENCE", "D"+"Setting broadcast");
    context.registerReceiver(onComplete,
            new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
    Log.d("REFERENCE", "F"+"Now Setting the uri table with");
}

BroadcastReceiver onComplete = new BroadcastReceiver() {

    public void onReceive(Context ctxt, Intent intent) {
        Log.d("REFERENCE", "E"+"Entering Broadcast");
        long referenceId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1);
        uri=( manager.getUriForDownloadedFile(referenceId));

    }
};
//TODO: Add Utility to remove all Cached Videos
//TODO: Add Utility to delete a single cached video after it has been watched.

public Uri getUri() {
    return uri;
}

}

So I have taken a look at examples from other people and implemented this.

仅当 Uri 具有 file 方案并且您对保存文件的目录具有写入权限时才有效。

How to delete a file from external storage android studio, using only Uri

很可能你没有。

如果您从 ACTION_OPEN_DOCUMENTACTION_CREATE_DOCUMENT 获得 Uri,请使用 fromSingleUri()Uri 包装在 DocumentFile 中,然后调用delete()DocumentFile.

对于任何其他 content Uri,欢迎您尝试在 ContentResolver 上调用 delete(),但不要指望它会起作用。不要求 ContentProvider 为您提供任何删除内容的方法。提供 ContentProvider 的应用程序应该有自己的方式允许用户删除内容。

对于那些不想通读我们的评论的人来说,这是我的问题的解决方案。首先,选择要下载到的目录。然后使用该文件路径并使用 delete() 功能。请记住,一旦您创建了一个带有文件夹名称的目录,您只需要引用文件夹名称而不是整个路径。这是我希望对您有所帮助的代码:

    String in= GenerateDirectory.createVideoDirectory(context);// Might be useless here.
    manager= (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
    Uri temp=Uri.parse(urlIn);
    Ringtone r= RingtoneManager.getRingtone(context, temp);
    String filename=(r.getTitle(context));
    DownloadManager.Request request= new DownloadManager.Request(temp);
    request.setDestinationInExternalPublicDir("/secretVideos", filename);
    uri=Uri.parse(in+"/"+filename);
    Log.d("REFERENCE", "Uri that is returned "+uri);
    request.setNotificationVisibility(Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
    manager.enqueue(request);

// 然后

 public void removeCache(){
    //TODO: Fix this. For some reason the Uri used gives invalid path name.
    Log.d("Delete", "Directory to find ... "+uri);
    File delete= new File(uri.getPath());
    if(delete.exists()){
        Log.d("Delete", "File Exists");
        if(delete.delete()){
            Log.d("Deleted", ""+uri);
        }
    }
}

// 我在哪里创建目录

 private int RESULT=0;
  public static String createVideoDirectory(Context context){
      String pathToExternalStorage = Environment.getExternalStorageDirectory().toString();
      File appDirectory = new File(pathToExternalStorage + "/" + "secretVideos");
      if(!appDirectory.exists()){
          Log.d("Directory","Directory DNE");
            if(appDirectory.mkdir()) {
             Log.d("Directory", "Directory  Created");

             //Log.d("Directory","Unable to create directory, using default directory");
            }
            else if(appDirectory.canWrite()){
                Log.d("Directory", "Permission given");
      }
            else{
                Log.d("Directory", "Lack of permission");
            }
      }

      else{
          Log.d("Directory","Already Exists");
      }


    return appDirectory.toString();
}
private void writeAndReadPermissions(Context context){
      if(ContextCompat.checkSelfPermission(context, permission.WRITE_EXTERNAL_STORAGE)!=PackageManager.PERMISSION_GRANTED){
        ActivityCompat.requestPermissions((Activity) context, new String[]{permission.WRITE_EXTERNAL_STORAGE, permission.READ_EXTERNAL_STORAGE}, RESULT);

      }
}