【问题标题】:Android delete directory using Media Store URIAndroid 使用 Media Store URI 删除目录
【发布时间】:2021-09-16 21:28:57
【问题描述】:

这是新的作用域存储。

var dlRequest = DownloadManager.Request(Uri.parse(urlToPhoto))
...
var file = File("somedir", filename) // File inside directory "somedir"
dlRequest.setDestinationInExternalPublicDir(Environment.DIRECTORY_PICTURES, file.path)

到目前为止一切顺利,照片下载到/Pictures/somedir/

现在我想删除目录和里面的所有文件。我该怎么做?

更新:使用范围存储我有read here 无法再通过路径访问文件,您必须使用媒体存储 URI。我可以获取URI并删除文件,但我仍然没有找到删除目录的解决方案。

【问题讨论】:

  • 所用设备的Android版本?
  • 你在滥用 File 类。 File 类用于文件。并且文件具有完整路径。 “somedir/filename”不是完整路径。试试 File.exists()。更好:dlRequest.setDestinationInExternalPublicDir(Environment.DIRECTORY_PICTURES, "somedir/filename")
  • 您无法在 Android 11+ 上删除该目录,因为它属于下载管理器。要删除文件,请使用您可以从 DownloadManager 获得的 uri。
  • 这更有意义,我使用的是 Android 11。必须有另一种方法将文件存储在子目录中,以便您之后删除该目录。或者您是说我需要从下载管理器中保存 URI?
  • 是的,保存所有的尿。您也可以为他们查询媒体商店。不知道。试试吧。

标签: android kotlin android-storage


【解决方案1】:

您可以使用内置的deleteRecursively() 函数来做到这一点:

val picturesDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)
File(picturesDir, "somedir").deleteRecursively()

请注意,自 Android 10 起,直接访问此目录已被弃用。

【讨论】:

  • 你的示例代码中的 somedir 是什么?
  • @Coop 点击链接!
  • 我知道这是一个File 对象。我已经梳理了几个小时的文档,这是搜索中出现的第一件事,它没有回答我的问题。
  • 所以如果我理解正确的话,你的问题不在于如何递归地删除目录,而是如何找到正确的路径?然后问题标题完全具有误导性。 setDestinationInExternalPublicDir() 方法的文档似乎非常清楚结果路径是什么。我更新了我的答案。我希望它有效,因为我没有机会测试它。
【解决方案2】:

仅供参考

我在我的生产应用代码上测试了@broot 的方法 (File.deleteRecursively()),它在我的 Android 8.1 设备上运行良好。

val downloadDirectory = File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), "tancolo")
println("TANCOLO===> download folder = ${downloadDirectory.absolutePath}")
val file = File(downloadDirectory, fileName)
...

显然,文件夹“tancolo”必须存在于父文件夹“Download”中,日志显示:download folder = /storage/emulated/0/Download/tancolo

然后我使用了deleteRecursively()的扩展方法,像这样:

//delete the folder "tancolo" and all files in it.
val directory = File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), "tancolo")
        try {
            val hasDeleted = directory.deleteRecursively()
            println("TANCOLO===> hasDeleted: $hasDeleted")
        } catch (exp: Exception) {
            println("TANCOLO===> exception: ${exp.message}")
        }

日志显示: TANCOLO===> hasDeleted: true

【讨论】:

    猜你喜欢
    • 2014-09-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-10
    • 2012-12-20
    • 2013-06-02
    • 2019-01-10
    • 1970-01-01
    相关资源
    最近更新 更多