如何使用路径删除文件

问题描述 投票:0回答:2

我正在构建一个应用程序,允许用户保存位图或共享它而不保存它。第二个功能不太起作用。我知道应用程序需要先将文件保存到设备上,然后才能在社交媒体应用程序上共享它,所以我的想法就是在文件成功共享后立即自动从设备中删除文件。我已经构建了一个尝试两种不同方法的删除方法,但都没有工作:

第一种方法:

public void deleteFile(String path){
        File file = new File(path);
        try {
            file.getCanonicalFile().delete();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

第二种方法:

public void deleteFile(String path){
    File file = new File(path);
    boolean deleted = file.delete();
}

我从分享方法中调用deleteFile(String)

public void shareMeme(Bitmap bitmap) {
    String path = MediaStore.Images.Media.insertImage(Objects.requireNonNull(getContext()).getContentResolver(), bitmap, "Meme", null);
    Uri uri = Uri.parse(path);

    Intent share = new Intent(Intent.ACTION_SEND);
    share.setType("image/*");
    share.putExtra(Intent.EXTRA_STREAM, uri);
    share.putExtra(Intent.EXTRA_TEXT, "This is my Meme");
    getContext().startActivity(Intent.createChooser(share, "Share Your Meme!"));

    deleteFile(path);
}
android file android-intent android-bitmap mediastore
2个回答
1
投票

关于你陈述的问题,insertImage()返回Uri的字符串表示。那Uri不是文件。在它上面调用getPath()是没有意义的,你不能删除任何基于该路径的东西。

更广泛地说,如果您打算立即删除内容:

  • 不要把它放在MediaStore
  • 不要共享它,因为在其他应用程序有机会对其进行任何操作之前,您将删除它

如果要共享,但删除它:

  • 不要把它放在MediaStore
  • 第二天,几小时或其他什么时候删除它,因为你没有办法知道其他应用程序何时完成内容

要在不使用MediaStore的情况下与其他应用分享图像:

  • 将图像保存到getCacheDir()中的文件(在Context上调用,例如ActivityService
  • 使用FileProvider将该文件提供给其他应用程序

除此之外:

  • 不要在ACTION_SEND中使用通配符MIME类型。您是提供要发送内容的人。您知道实际的MIME类型。用它。
  • 请注意,没有要求ACTION_SEND活动同时尊重EXTRA_TEXTEXTRA_STREAM。大多数人似乎这样做,但这种行为超出了ACTION_SEND规范。
  • 请注意,insertImage()在Android Q上已弃用。

0
投票

首先,你需要检查你的file是否存在,(也许你设置了错误的路径?)。然后删除file

        File file = new File(path);
        if (file.exists()){
            if (file.delete()) {
              Toast.makeText(this, "file Deleted :" + path, Toast.LENGTH_SHORT).show();
              } else {
              Toast.makeText(this, "file not Deleted :" + path, Toast.LENGTH_SHORT).show();

              }
        }
© www.soinside.com 2019 - 2024. All rights reserved.