Write a new file in selected directory with OpenDocumentTree: transform Uri in path

292 views Asked by At

My app has to save a new excel file in a user-selected directory.

The user select the directory with OpenDocumentTree picker directory picker. This intent returns an Uri.

I'm not able to transform Uri in path for the write function. How can I do? Thanks a lot.

final ActivityResultLauncher<Uri> mDirRequest = registerForActivityResult(
        new ActivityResultContracts.OpenDocumentTree(),
        new ActivityResultCallback<Uri>() {
            @Override
            public void onActivityResult(Uri result) {

                path = somethingIdontknow;

                try {
                    File file = new File(path, "goofy.xlsx");
                    FileOutputStream out = new FileOutputStream(file);
                    workbook.write(out);
                    out.close();

                }
                catch (Exception e) {
                    e.printStackTrace();
                }

            }
        });

......

mDirRequest.launch(Uri.parse(DocumentsContract.EXTRA_INITIAL_URI));

I tried to implement a lot of suggestions from stackoverflow, but I've not resolved the problem.

2

There are 2 answers

2
blackapps On

You will not transform an uri in a path to begin with.

You can create a DocumentFile instance for the obtained uri.

After that use DocumentFile:createFile() to get an uri for the created file for which you open an InputStream and write to it.

7
Muhamad Kheder On

you can use the ContentResolver and the openFileDescriptor method to get a ParcelFileDescriptor object.

Here is an example how it can looks like:

final ActivityResultLauncher<Uri> mDirRequest = registerForActivityResult(
    new ActivityResultContracts.OpenDocumentTree(),
    new ActivityResultCallback<Uri>() {
        @Override
        public void onActivityResult(Uri result) {

            Uri fileUri = Uri.withAppendedPath(result, "pippo.xlsx");

            ContentResolver resolver = getContentResolver();
            try {
                OutputStream outputStream = resolver.openOutputStream(fileUri);
                workbook.write(outputStream);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    });