如何在不使用 FileOutputStream 的情况下使用 SAF 附加文件内容

How to append file content with SAF without using FileOutputStream

FileOutputStream 允许附加一个文件,只需在其构造函数中将附加属性设置为 true,不幸的是,由于直接路径限制和文件写入,无法使用 SAF FileOutputStream

resolver = getContentResolver();
OutputStream os = resolver.openOutputStream(source_uri);
PrintWriter out = new PrintWriter(new OutputStreamWriter(os));
out.print(somestring);
out.flush();
out.close();

如果我使用 out.append(somestring); 而不是 out.print(somestring);,则行为完全相同并且文件内容被替换,但我希望每次调用时将新输入附加到文件的现有内容.

openOutputStream()有两种形式。您正在使用的单参数版本相当于调用模式为 "w" 的双参数版本。对于附加操作,请尝试使用 "wa" 作为模式的双参数版本:

OutputStream os = resolver.openOutputStream(source_uri, "wa");

有关更多信息,请参阅 the documentation