4

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.

Dims
  • 47,675
  • 117
  • 331
  • 600

1 Answers1

5

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.

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491
  • `java.io.File` is also not necessary a file. – Dims Feb 04 '17 at 17:33
  • 2
    @Dims: It is, insofar as any given `File` object either points to a file or is invalid. A `Uri`, instead, can point to lots of things. For example, `http://stackoverflow.com/questions/42043114/how-to-write-to-documentfile-in-android-programmatically/42043137` is a valid `Uri`. It does not point to a file on any client device. – CommonsWare Feb 04 '17 at 17:37
  • Okay, I see this. – Dims Feb 04 '17 at 18:26