转换文件:Android中的Uri到文件

新手上路,请多包涵

android.net.Uri 对象(包含 file: 类型)转换为 Android 中的 File 对象的最简单方法是什么?

我尝试了以下方法,但它不起作用:

 File file = new File(Environment.getExternalStorageDirectory(), "read.me");
Uri uri = Uri.fromFile(file);
File auxFile = new File(uri.toString());
assertEquals(file.getAbsolutePath(), auxFile.getAbsolutePath());

原文由 hpique 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.3k
2 个回答

你想要的是…

 new File(uri.getPath());

… 并不是…

 new File(uri.toString());

笔记
  1. For an android.net.Uri object which is named uri and created exactly as in the question , uri.toString() returns a String in the format "file:///mnt/sdcard/myPicture.jpg" ,而 uri.getPath() 返回 String 格式为 "/mnt/sdcard/myPicture.jpg"
  2. 我了解 Android 中的文件存储存在细微差别。我在这个答案中的意图是准确回答提问者的问题,而不是进入细微差别。

原文由 Adil Hussain 发布,翻译遵循 CC BY-SA 4.0 许可协议

经过大量搜索并尝试了不同的方法,我发现这个适用于不同的 Android 版本:首先复制这个函数:

     fun getRealPathFromUri(context: Context, contentUri: Uri): String {
        var cursor: Cursor? = null
        try {
            val proj: Array<String> = arrayOf(MediaStore.Images.Media.DATA)
            cursor = context.contentResolver.query(contentUri, proj, null, null, null)
            val columnIndex = cursor?.getColumnIndexOrThrow(MediaStore.Images.Media.DATA)
            cursor?.moveToFirst()
            return columnIndex?.let { cursor?.getString(it) } ?: ""
        } finally {
            cursor?.close()
        }
    }

然后,生成一个像这样的文件:

 File(getRealPathFromUri(context, uri))

原文由 Mohammad Derakhshan 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题