You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android中如何将文档URI保存到SharedPreferences并加载文件路径?

问题分析与解决

你保存的/document/document:1000017239是Content URI,并非真实的本地文件路径,直接将其当作文件路径使用自然无法加载对应文件。以下是具体修正方案:

1. 修正保存逻辑

不要尝试转换为文件路径后保存,直接存储Uri的字符串形式即可——Content URI是系统识别文件的标准标识,比本地路径更可靠(避免路径变动、无真实路径的云端文件等问题)。同时注意apply()和commit()无需重复调用:

Uri fileUri = intent.getData();
SharedPreferences pref = Properties.getSharedPreferences(this);
pref.edit()
    .putString(Properties.FILE_URI, fileUri.toString())
    .apply(); // apply()异步提交已足够,无需额外调用commit()

2. 加载时的正确处理

从SharedPreferences取出Uri字符串后,先转换为Uri对象,再通过ContentResolver直接操作文件内容,而非试图获取本地路径:

String uriString = pref.getString(Properties.FILE_URI, "");
if (!uriString.isEmpty()) {
    Uri fileUri = Uri.parse(uriString);
    // 通过ContentResolver打开文件输入流
    try (InputStream is = getContentResolver().openInputStream(fileUri)) {
        // 在此处理文件内容,例如读取字节、转换为字符串等
    } catch (IOException e) {
        e.printStackTrace();
    }
}

3. 若确实需要本地文件路径(仅限本地可访问文件)

如果你的场景必须用到真实本地路径,可通过ContentResolver查询MediaStore获取,但此方法仅对本地媒体文件有效,对云端或其他应用托管的文件可能返回null:

private String getRealLocalPath(Uri uri) {
    String[] projection = {MediaStore.Files.FileColumns.DATA};
    Cursor cursor = getContentResolver().query(uri, projection, null, null, null);
    if (cursor != null) {
        int columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Files.FileColumns.DATA);
        cursor.moveToFirst();
        String localPath = cursor.getString(columnIndex);
        cursor.close();
        return localPath;
    }
    return null;
}

内容的提问来源于stack exchange,提问作者정희용

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.16 19:02:41