gpt4 book ai didi

java - 如何在首选项中正确地将 URI 保存到文件

转载 作者:行者123 更新时间:2023-12-04 07:19:56 25 4
gpt4 key购买 nike

在我的应用程序中,我希望用户选择一个应该用于读取\写入数据的文件,然后“记住”这个文件 URI,以便在应用程序重新启动时使用。
我使用以下方法从用户那里获取文件 URI:

Intent intent = new Intent(Intent.ACTION_CREATE_DOCUMENT);
...
startActivityForResult(intent, CREATE_FILE);
以及所有相关的东西,效果很好。
然后我尝试将 URI 存储在首选项中:
SharedPreferences sharedPreferences = context.getSharedPreferences(PREFERENCES_FILE_KEY, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(DATA_FILE_NAME_KEY, dataFileUri.getPath());
editor.apply();
Log.i(TAG, "Saved data file URI: " + dataFileUri.getPath());
在这里我注意到存储的 URI 看起来像: /document/31这对我来说似乎不正确。
在应用程序重新启动时,我从首选项中检索 URI:
SharedPreferences sharedPreferences = context.getSharedPreferences(PREFERENCES_FILE_KEY, Context.MODE_PRIVATE);
String dataFileText = sharedPreferences.getString(DATA_FILE_NAME_KEY, null);
Log.i(TAG, "File uri from preferences: " + dataFileText);
return Optional.ofNullable(dataFileText)
.map(File::new)
.map(Uri::fromFile);
显然我得到了相同的 URI: /document/31这显然不再适用于打开文件:
java.io.FileNotFoundException: /document/31
这是我尝试读取文件的方式:
InputStream inputStream = context.getContentResolver().openInputStream(uri);
我已经尝试了提出的解决方案:
  • https://stackoverflow.com/a/39850724/4174003
  • https://www.dev2qa.com/how-to-get-real-file-path-from-android-uri/
  • 使用 ContentResolver.query..以类似的方式:https://stackoverflow.com/a/16511111/4174003

  • 所有这些都不起作用,对我来说看起来很奇怪和丑陋。

    Android 中通过应用程序启动/停止周期保留 URI 以供使用的正确方法是什么?

    最佳答案

    不要保存 URI 的路径部分,请尝试使用 dataFileUri.toString() 将整个 URI 保存为文本。 .它应该类似于“content://document/31”。
    SharedPreferences 阅读后使用 Uri.parse(uriString)恢复URI。

    关于java - 如何在首选项中正确地将 URI 保存到文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68566450/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com