问题
I let the user select a file from the sdcard to upload to my server and save the Uri
that gets returned to me in onActivityResult
example:
file:///storage/emulated/0/Download/menu-4.27.13.pdf
when I try to convert it to a byte array to send to the server I get the 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();
}
}
}
stack trace
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)
is that not what the File
objects as a string when its initialized? Why am I getting the FileNotFoundException
when I have the Uri
returned to me when the user selected the file
回答1:
Your Uri
contains the file:
scheme, which you need to remove. Using Uri.parse
, you figure the Uri contained in your String, using uri.getPath()
, you extract the file path from the uri :
Uri uri = Uri.parse(fileURI);
File pdf = new File(uri.getPath());
回答2:
Your code is correct, maybe the file is not present or the path is wrong. See the stack trace. The first line itself tells the whole problem. Try accessing some other file and parse the filePath first using URI
来源:https://stackoverflow.com/questions/19772856/getting-file-from-sdcard-with-uri