Reputation: 217
For an assignment, we are required to be able to save a custom file type and then be able to read it back in again. I figured I could use the FileInputStream class so that I could easily just use myInStream.read() to get all of the information I need from the file. However, I've run into a problem with getting the file into the FileInputStream. I was able to get the URI, but it seems the method I used to get the URI makes a URI type that is incompatible with the File class. I have the following code in my onActivityResult() right before I start reading:
Uri pickedFile = data.getData();
File myFile = new File(pickedFile);
FileInputStream inStream = new FileInputStream(myFile);
On the second line it says "Cannot resolve constructor 'File(android.net.Uri)'", so I'm assuming I must have to convert the URI to a different format, but I have no idea how to go about it. Any help would be much appreciated!
EDIT: For future reference the fixed code looks like this: Uri pickedFile = data.getData(); InputStream inStream = getContentResolver().openInputStream(pickedFile);
Upvotes: 4
Views: 9792
Reputation: 726
I do it like this:
FileInputStream importdb = new FileInputStream(_context.getContentResolver().openFileDescriptor(uri, "r").getFileDescriptor());
Upvotes: 14
Reputation: 1006914
I'm assuming I must have to convert the URI to a different format
No. A Uri
is an opaque handle to some content, such as https://stackoverflow.com/questions/42893406/putting-a-uri-into-a-fileinputstream
. It is not a file.
You do not show where your Uri
is coming from. My guess, given the named pickedFile
, is that you are using ACTION_GET_CONTENT
or ACTION_OPEN_DOCUMENT
. In neither case is the user picking a file.
If my guess is correct as to where the Uri
is coming from, that Uri
will have either a file
scheme or a content
scheme. You can get an InputStream
on either type of Uri
the same way: call openInputStream()
on a ContentResolver
. You get a ContentResolver
by calling getContentResolver()
on a Context
, such as your Activity
or Service
.
Upvotes: 5