什么是在Android中从 file:
android.net.Uri
转换为 File
的最简单方法?
尝试以下但它不起作用:
final File file = new File(Environment.getExternalStorageDirectory(), "read.me");
Uri uri = Uri.fromFile(file);
File auxFile = new File(uri.toString());
assertEquals(file.getAbsolutePath(), auxFile.getAbsolutePath());
16 回答
使用
直接复制文件 . 另见:
https://developer.android.com/guide/topics/providers/document-provider.html
使用Kotlin它更容易:
或者,如果您使用Kotlin extensions for Android:
Android + Kotlin
implementation 'androidx.core:core-ktx:{latestVersion}'
uri.toFile()
Android + Java
刚刚移到顶部;)
你想要的是......
... 并不是...
NOTE:
uri.toString()
返回格式为:"file:///mnt/sdcard/myPicture.jpg"
的字符串,而uri.getPath()
返回格式为:"/mnt/sdcard/myPicture.jpg"
的字符串 .搜索了很长时间后,这对我有用:
编辑:对不起,我之前应该测试得更好 . 这应该工作:
URI是java.net.URI .
这些都不适合我 . 我发现这是一个有效的解决方案 . But my case is specific to images .
Best Solution
Create one simple FileUtil java class & use to creat, copy and rename the file
我使用
uri.toString()
和uri.getPath()
但不适合我 . 我终于找到了这个解决方案User FileUtil class in your code
我这样做的方式如下:
所以基本上我首先尝试使用一个文件,即相机拍摄的照片并保存在SD卡上 . 这对于返回的图像不起作用:Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);那种情况需要通过
getRealPathFromURI()
函数将Uri转换为实际路径 . 所以结论是它取决于你想要转换为File的Uri的类型 .@CommonsWare很好地解释了所有事情 . 我们真的应该使用他提出的解决方案 .
顺便说一下,只有在查询
ContentResolver
时我们可以依赖的信息才是这里提到的文件名和大小:Retrieving File Information | Android developers如您所见,有一个界面
OpenableColumns
只包含两个字段:DISPLAY_NAME和SIZE .在我的情况下,我需要检索有关JPEG图像的EXIF信息,并在发送到服务器之前根据需要旋转它 . 为此,我使用
ContentResolver
和openInputStream()
将文件内容复制到临时文件中对于这种情况,特别是在Android上,字节的方式通常更快 .
有了这个,我通过设置一个类_932383来解决它,它负责处理从文件到文件的读/写字节和一个类
UriHelper
,它负责找出Uri的路径和权限 .据我们所知,
string.getBytes((charset == null) ? DEFAULT_CHARSET:charset)
可以帮助我们将您想要的字符串传输到您需要的字节 .如何让UriHelper和FileHelper将Uri注释的图片复制到一个文件中,你可以运行:
关于我的UriHelper:
}
关于我的FileHelper:
}
对于那里寻找图像解决方案的人来说,特别是在这里 .
文件imageToUpload = new File(新URI(androidURI.toString()));如果这是您在外部存储中创建的文件,则可以正常工作 .
例如file:/// storage / emulated / 0 /(某些目录和文件名)
public String getRealPathFromURI(Uri uri){
然后使用从URI获取文件:
通过以下代码,我能够将adobe应用程序共享的pdf文件作为流并保存到android应用程序路径中
基于@JacekKwiecień的扩展基础将 image uri 转换为 file
如果我们使用
File(uri.getPath())
,它将无法正常工作如果我们使用android-ktx的扩展名,它仍然无效,因为https://github.com/android/android-ktx/blob/master/src/main/java/androidx/core/net/Uri.kt