android– 用Uri从SD卡获取文件

android– 用Uri从SD卡获取文件,第1张

概述我让用户从SD卡中选择一个文件上传到我的服务器并保存在onActivityResult中返回给我的Uri例:file:///storage/emulated/0/Download/menu-4.27.13.pdf当我尝试将其转换为字节数组以发送到服务器时,我得到FileNotFoundExceptionif(!fileURI.equals("")){Filepdf=newFi

我让用户从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

解决方法:

您的Uri包含文件:scheme,您需要删除它.使用Uri.parse,您可以使用uri.getPath()来计算String中包含的Uri,从uri中提取文件路径:

Uri uri = Uri.parse(fileURI);file pdf = new file(uri.getPath());
总结

以上是内存溢出为你收集整理的android – 用Uri从SD卡获取文件全部内容,希望文章能够帮你解决android – 用Uri从SD卡获取文件所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/1116407.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-29
下一篇 2022-05-29

发表评论

登录后才能评论

评论列表(0条)

保存