Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Putting a URI into a FileInputStream

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);

like image 554
user3713569 Avatar asked Sep 13 '25 00:09

user3713569


1 Answers

I do it like this:

FileInputStream importdb = new FileInputStream(_context.getContentResolver().openFileDescriptor(uri, "r").getFileDescriptor());
like image 138
Nikolai Ehrhardt Avatar answered Sep 15 '25 13:09

Nikolai Ehrhardt