如何以编程方式写入 Android 中的 DocumentFile?

How to write to DocumentFile in Android programmatically?

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

假设我调用了这个方法,它返回了 true。还假设此对象代表 "raw" 文件。

现在我该如何做呢?

即,如何将 "Hello world" 文本写入该文件?

谢谢。

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

不一定是文件。

要写入由 DocumentFile 标识的文档,请在 DocumentFile 上调用 getUri() 以将 Uri 写入文档。将其传递给 ContentResolver 上的 openOutputStream()。然后,写入流,flush()流,close()流。基本上,一旦你得到 OutputStream,普通的 Java I/O 就会接管。