Search code examples
androidstorage-access-framework

Create blank file inside directory with Uri


I am trying to create a file inside a directory using Uri. For the new file to be created, I do not have the Uri, but I do have for the directory inside which I want to create the file. I am following this guide: https://developer.android.com/training/data-storage/shared/documents-files#grant-access-directory

So now I have persistent access to (say) [Internal storage]/MyFilesCollection I also have the Uri to access it. I want to create a file inside this directory, basically (say) [Internal storage]/MyFilesCollection/myFile.txt

I do not want to use Intent.ACTION_CREATE_DOCUMENT as it opens the system picker for every file I want to create. Also I have persistent write access to the folder. So is there any way to create the file without using intents?

Edit: Code used to gain persistent access:

val contentResolver = applicationContext.contentResolver
val takeFlags: Int = Intent.FLAG_GRANT_READ_URI_PERMISSION or
        Intent.FLAG_GRANT_WRITE_URI_PERMISSION
contentResolver.takePersistableUriPermission(uri, takeFlags)

Thanks.


Solution

  • I am going to guess that you are using ACTION_OPEN_DOCUMENT_TREE to get the Uri in the first place. If so:

    Step #1: Use DocumentFile.fromTreeUri() to get a DocumentFile associated with the Uri that you got from ACTION_OPEN_DOCUMENT_TREE

    Step #2: Call createFile() on that DocumentFile to get a DocumentFile representing the document that you wish to place in this tree

    Step #3: Call getUri() on that new DocumentFile to get a Uri representing the document

    Step #4: Call openOutputStream() on a ContentResolver, passing in that Uri, to get an OutputStream, which you can use to write to the document