为什么Android URI路径错误?

Android URI wrong path why?

提问人:Bisser Milanov 提问时间:9/16/2023 最后编辑:Stephen CBisser Milanov 更新时间:9/17/2023 访问量:46

问:

我有一个文件

File tempFile = ....// creating the file
String fPath = temFile.getPath(); //this will return - /storage/emulated/0/Pictures/A
//After that I get the URI
URI uuu = FileProvider.getUriForFile(this,
                        "com.example....app.provider",
                        tempFile);
String uPath = uuu.getPath(); // this will return - /external_files/Pictures/A
   

如何从 URI (/storage...) 获取第一个路径。我不能对第二个(/external...我与第二条路径一起使用的每个函数都会导致错误。

目前,我所做的是创建文件,获取 URI,并获取路径并记住两者,以便稍后使用我需要的任何文件。难道不能只保留 URI 并在需要时获得正确的路径吗?

或者,也许我应该只保留路径并在需要时创建 URI。

我已经在上面解释过了

Java Android 文件 路径 URI

评论

1赞 blackapps 9/16/2023
String uPath = uuu.getPath(); // this will return - /external_files/Pictures/A这是没有道路的。这是一条无稽之谈的道路。查看 uuu.toString() 以查看路径的内容方案。
0赞 blackapps 9/16/2023
只需记住您的文件路径以备后用。如果要让其他应用读取或写入您的文件,则只需要 uri fo 访问权限。
0赞 blackapps 9/16/2023
如果你比较 uuu.toString() 和 uuu.getPath() 并查看你的 FileProvider 路径 xml 文件,你就会知道这个 /external_files/ 的来源。是的,目前您了解 getUriForFile() 的工作原理,您可以从文件提供程序 uri 解码您的文件路径。
0赞 blackapps 9/16/2023
Is it not possible to keep just the URI and get the proper path when we need it?您可以保留 uri 并在需要时使用 uri。没有理由从 uri 获取路径,因为您可以使用 uri 读取和写入文件,甚至删除它。

答:

0赞 marcinj 9/17/2023 #1

您看到的两个路径之间的区别是因为一个是文件系统路径:/storage/emulated/0/Pictures/A,另一个是 android FileProvider 提供的内容 URI 路径 /external_files/Pictures/A。

无法直接从 FileProvider 返回的 URI 获取实际文件路径。URI 是 content://scheme,它不是 file://scheme。FileProvider 提供对实际文件位置的抽象。如果需要真实的文件路径,则应在创建文件时将其存储。

如果确定只在自己的应用中使用文件,则可以选择保留文件路径,并在需要时创建 URI 以共享它。您可以在需要时使用 FileProvider.getUriForFile() 创建 URI。

根据我的经验,只有当我必须向其他应用程序提供对本地文件的访问时,我才会使用 FileProvider。 在内部,我使用了此类文件的已知位置 - 使用它们的绝对路径。