java - 如何使用内容uri检查文件是否存在

标签 java android react-native kotlin nativescript

我有一个音频文件的内容 uri,它是我从选择器 Intent 中获得的。

content://com.mi.android.globalFileexplorer.myprovider/external_files/KannadaGeeta/11CHAPTER10.mp3

我只是将上面的 uri 保存在数据库中。

现在,当用户再次打开我的应用时。我需要通知他他选择的最后一个 mp3 文件是否存在。如果存在那么只有我必须允许他继续否则我需要通知重新下载文件。

但我完全卡在这里,我不知道如何使用其内容 uri 检查文件是否存在。

请帮助我解决我的问题。

最佳答案

方法一:- 好的,由于 Android 团队出于安全原因决定弃用 getExternalStorageDirectory。他们没有妥善解决很多问题。

对于这个问题我没有找到任何合适的答案。无论如何,这是使用已弃用方法的解决方法。

        var uri = Uri.parse("content://com.mi.android.globalFileexplorer.myprovider/external_files/KannadaGeeta/11CHAPTER10.mp3")
        var vidPath = uri.path
        vidPath = vidPath?.replace("external_files",Environment.getExternalStorageDirectory().toString())
        val file = File(vidPath)

        if (file.exists()) {
            println("log yes $file")
        } else {
            println("log no $file")
        }

这会工作得很好,但由于已弃用的方法,您可以使用它。

方法二:- 另一种方法是使用 ACTION_OPEN_DOCUMENT 然后在 onActivityResult 中必须添加

val contentResolver = applicationContext.contentResolver
val takeFlags: Int = Intent.FLAG_GRANT_READ_URI_PERMISSION or       
                     Intent.FLAG_GRANT_WRITE_URI_PERMISSION
contentResolver.takePersistableUriPermission(selectedVideoUri!!, takeFlags)

然后,最后使用未过期的 content uri,可以检查文件是否存在。

DocumentFile.fromSingleUri(Uri.parse(contentUriStringfromdatabase)).exists()

关于java - 如何使用内容uri检查文件是否存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62878883/

相关文章:

reactjs - 使图标在 React Native 中可供选择,而不是通过 props 发送它们

java - 我如何使用 Weblogic 构建 Rest + EJB?

java - 用字母表中的下一个辅音替换字符串中的辅音

android - OpenGL (ES) -- 截锥体和正视体有什么区别?

react-native - 任务 :app:bundleReleaseJsAndAssets_SentryUpload FAILED

javascript - React Native 在运行时动态注入(inject)组件

java - 在Java中将十进制转换为罗马数字?

java - 如何使用 Google Truth(单元测试)使用两个元素的属性之一来比较两个元素

android - 使用卡片 View 在回收器 View 中加载文本太慢

java.lang.NoSuchMethodError : No static method - Firebase issue despite not using FirebaseMessagingService?