从sd卡中获取文件的Uri

3

我让用户从SD卡选择要上传到服务器并在onActivityResult中将返回给我的Uri保存下来。

例如:

file:///storage/emulated/0/Download/menu-4.27.13.pdf

当我尝试将它转换为字节数组以发送到服务器时,我遇到了FileNotFoundException

if(!fileURI.equals("")){
    File pdf = new File(fileURI);
    try 
    {
        FileInputStream fin = new FileInputStream(pdf);

        byte fileContent[] = new byte[(int)pdf.length()];
        fin.read(fileContent);
        fin.close();

        String pdfString = Base64.encode(fileContent);
        sb.append(pdfString);
    } 
    catch (FileNotFoundException e) 
    {
        e.printStackTrace();
    }
    catch(IOException ioe)
    {
        ioe.printStackTrace();                      
    }
}

}

堆栈跟踪

11-04 11:57:30.597: W/System.err(13531): java.io.FileNotFoundException: /file:/storage/emulated/0/Download/menu-4.27.13.pdf: open failed: ENOENT (No such file or directory)
11-04 11:57:30.597: W/System.err(13531):    at libcore.io.IoBridge.open(IoBridge.java:409)
11-04 11:57:30.607: W/System.err(13531):    at java.io.FileInputStream.<init>(FileInputStream.java:78)
11-04 11:57:30.607: W/System.err(13531):    at com.ecm2.mobilemap.services.MessageService.getModifiedElements(MessageService.java:2755)
11-04 11:57:30.617: W/System.err(13531):    at com.ecm2.mobilemap.services.MessageService.callSync(MessageService.java:2433)
11-04 11:57:30.617: W/System.err(13531):    at com.ecm2.mobilemap.services.MessageService.onHandleIntent(MessageService.java:190)
11-04 11:57:30.627: W/System.err(13531):    at android.app.IntentService$ServiceHandler.handleMessage(IntentService.java:65)
11-04 11:57:30.627: W/System.err(13531):    at android.os.Handler.dispatchMessage(Handler.java:99)
11-04 11:57:30.637: W/System.err(13531):    at android.os.Looper.loop(Looper.java:137)
11-04 11:57:30.637: W/System.err(13531):    at android.os.HandlerThread.run(HandlerThread.java:61)
11-04 11:57:30.637: W/System.err(13531): Caused by: libcore.io.ErrnoException: open failed: ENOENT (No such file or directory)
11-04 11:57:30.647: W/System.err(13531):    at libcore.io.Posix.open(Native Method)
11-04 11:57:30.657: W/System.err(13531):    at libcore.io.BlockGuardOs.open(BlockGuardOs.java:110)
11-04 11:57:30.657: W/System.err(13531):    at libcore.io.IoBridge.open(IoBridge.java:393)

这不是当初始化File对象时返回的字符串吗?为什么我在拥有用户选择文件返回的Uri时会出现FileNotFoundException错误?


也许你可以使用内容解析器请参见 - https://dev59.com/smLVa4cB1Zd3GeqPvVnJ - ranjk89
日志中的文件路径“/file:/storage/emulated/0/Download/menu-4.27.13.pdf”不正确。可能是您获取文件路径的方式不正确。 - jagmohan
2个回答

11

你的Uri包含file:方案,你需要删除它。使用Uri.parse,你可以找出String中包含的Uri,再使用uri.getPath()从Uri中提取文件路径:

Uri uri = Uri.parse(fileURI);
File pdf = new File(uri.getPath());

这个问题让我花了很长时间才找到答案,但是当你想明白后就很显然了。谢谢。 - danielcooperxyz
在这种情况下,fileURI是什么? - Kala J
1
@KalaJ:参考问题:例如:file:///storage/emulated/0/Download/menu-4.27.13.pdf - njzk2
经过一点时间终于弄明白了。谢谢! - Kala J
你救了我的一天! - Hamzeh Soboh

0

你的代码是正确的,可能文件不存在或路径错误。 查看堆栈跟踪。第一行就能说明问题所在。尝试访问其他文件并使用URI首先解析filePath。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接