从Uri读取文件给出java.io.FileNotFoundException:打开失败:ENOENT [英] Reading File from Uri gives java.io.FileNotFoundException: open failed: ENOENT
问题描述
当使用ACTION_GET_CONTENT
意图拾取图像时,我得到一个无法从中打开文件的URI.如果我尝试打开文件,如下所示:
When picking an image using an ACTION_GET_CONTENT
intent, I get a URI that I can't open the file from. If I try to open the file, like this:
InputStream in = new FileInputStream(new File(uri.getPath()));
它具有以下异常:
03-11 15:14:36.132 20557-20557/my.package W/System.err﹕ java.io.FileNotFoundException: /document/image:9537: open failed: ENOENT (No such file or directory)
03-11 15:14:36.138 20557-20557/my.package W/System.err﹕ at libcore.io.IoBridge.open(IoBridge.java:456)
03-11 15:14:36.138 20557-20557/my.package W/System.err﹕ at java.io.FileInputStream.<init>(FileInputStream.java:76)
/document/image:9537
似乎确实是错误的路径,但是如何获得正确的路径?
/document/image:9537
seems to indeed be an incorrect path, but how do I get the correct path?
我使用此逻辑打开图像选择器:
I use this logic to open the image picker:
Intent photoPickerIntent = new Intent(Intent.ACTION_GET_CONTENT);
photoPickerIntent.setType("image/*");
photoPickerIntent.putExtra("return-data", false);
startActivityForResult(Intent.createChooser(photoPickerIntent, "Complete action using"), PICK_FROM_FILE);
并像这样在onActivityResult中检索Uri:
And retrieve the Uri in the onActivityResult like this:
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
....
Uri uri = data.getData();
我需要获取文件进行解码以使其更小.
I need to get the file to do decoding to make it smaller.
推荐答案
如果我尝试打开文件,如下所示:
If I try to open the file, like this:
这不适用于大多数现代Android设备.您很可能收到了content:
Uri
.这在较新版本的Android上是很正常的.未来的Android版本可能会阻止file:
Uri
值.
That will not work for most modern Android devices. Most likely, you received a content:
Uri
. This is fairly normal on newer versions of Android. Future versions of Android might block file:
Uri
values.
我需要获取文件进行解码以使其更小.
I need to get the file to do decoding to make it smaller.
不必与给定的Uri
关联的文件. Uri
可能指向:
There does not have to be a file associated with a given Uri
. That Uri
might point to:
- 外部存储中的本地文件
- 内部存储中另一个应用程序的本地文件
- 可移动存储中的本地文件
- 已加密且需要动态解密的本地文件
- 保存在数据库的
BLOB
列中的字节流 - 需要先由其他应用下载的内容
- ...等等
- A local file on external storage
- A local file on internal storage for the other app
- A local file on removable storage
- A local file that is encrypted and needs to be decrypted on the fly
- A stream of bytes held in a
BLOB
column in a database - A piece of content that needs to be downloaded by the other app first
- ...and so on
使用ContentResolver
和openInputStream()
在Uri
指向的内容上获取InputStream
.然后,将其传递给您的解码逻辑,例如BitmapFactory
及其decodeStream()
方法.
Use a ContentResolver
and openInputStream()
to get an InputStream
on the content pointed to by the Uri
. Then, pass that to your decoding logic, such as BitmapFactory
and its decodeStream()
method.
这篇关于从Uri读取文件给出java.io.FileNotFoundException:打开失败:ENOENT的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!