widavies
widavies

Reputation: 976

Android: Converting a URI to File

I'm working on an app that allows users to create backup files and then re-import them with a file chooser. I export the file using the following code:

Intent intent = new Intent(Intent.ACTION_CREATE_DOCUMENT);
intent.setType("application/*");
startActivityForResult(intent, Constants.FILE_CHOOSER);

The code returns a URI in onActivityResult():

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if(requestCode == Constants.FILE_CHOOSER) {
         Uri uri = data.getData();
    }

I have a File that references a file within my app's local storage that contains data. I would simply like to take the file from the app's internal storage and save it to whatever directory the user selected. I can't get it to work. How do I convert the returned Uri into a File so I can write data more easily?

Upvotes: 0

Views: 908

Answers (1)

CommonsWare
CommonsWare

Reputation: 1006869

I would simply like to take the file from the app's internal storage and save it to whatever directory the user selected

The user didn't select a directory. The user is creating a document, where the Uri points to that document.

How do I convert the returned Uri into a File so I can write data more easily?

You don't, any more than you convert an HTTPS URL into a File so you can write data more easily.

Use ContentResolver and openOutputStream() to open an OutputStream on the (empty) document created by ACTION_CREATE_DOCUMENT and identified by the returned Uri. Then, use standard Java I/O to copy the bytes from your file (e.g., via a FileInputStream) to the OutputStream.

Upvotes: 1

Related Questions