如何使用路径删除文件

How to delete a file using the path

我正在构建一个允许用户保存位图或在不保存的情况下共享位图的应用程序。第二个功能不太好用。我知道该应用程序需要先将文件保存到设备上,然后才能在社交媒体应用程序上共享文件,因此我的想法是,在文件成功共享后立即自动从设备上删除文件。我构建了一个删除方法,尝试了两种不同的方法,但都没有奏效:

第一种方法:

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

首先,您需要检查您的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();

              }
        }

关于您提出的问题,insertImage() returns Uri 的字符串表示形式。 Uri 不是文件。在其上调用 getPath() 是没有意义的,并且您无法删除基于该路径的任何内容。

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

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

如果你想分享它,但又删除它:

  • 不要放在MediaStore
  • 第二天或几小时后删除它,因为您无法知道其他应用何时处理完内容

在不使用 MediaStore:

的情况下与另一个应用程序共享图像
  • 将图像保存到 getCacheDir() 中的文件(在 Context 中调用它,例如 ActivityService
  • 使用 FileProvider 使该文件可供其他应用程序使用

除此之外:

  • 不要在 ACTION_SEND 中使用通配符 MIME 类型。 是提供要发送的内容的人。 知道实际的 MIME 类型。使用它。

  • 请注意,ACTION_SEND activity 不需要同时满足 EXTRA_TEXTEXTRA_STREAM。大多数似乎都这样做,但这种行为超出了 ACTION_SEND 规范。

  • 请注意,insertImage() 在 Android Q 上已弃用。