Android:从 API 中的现有 URI 覆盖文件 29

Android: overwrite file from an existing URI in API 29

以下代码采用 String 并将内容保存到现有文件 Uri。这些代码在 Android pre API 29.

中运行良好
public void saveFile(String text, Uri existingSourceUri)
{
    try {

    ContentResolver cr = getContentResolver();
    OutputStream os = cr.openOutputStream(existingSourceUri);

    os.write(text.getBytes());
    os.flush();
    os.close();


    } catch (Exception e) {
       //show error message
    }
}

对于 Android API 29+,行为不稳定。例如,如果函数第一次调用时带有一些 text,则文件会被正确保存。但是,如果第二次text为空,则文件没有保存。

有什么帮助吗?

cr.openOutputStream(existingSourceUri, "wt");