androidfiledocumentfile

How to write to DocumentFile in Android programmatically?


Android API has DocumentFile class. This class has canWrite() method.

Suppose I called this method and it returned true. Also suppose this object was representing "raw" file.

Now how can I do what it said I can?

Namely, how to write "Hello world" text into that file?

Thanks.


Solution

  • Namely, how to write "Hello world" text into that file?

    It is not necessarily a file.

    To write to the document identified by that DocumentFile, call getUri() on that DocumentFile to get the Uri to the document. Pass that to openOutputStream() on a ContentResolver. Then, write to the stream, flush() the stream, and close() the stream. Basically, once you get the OutputStream, from there ordinary Java I/O takes over.