Truncate existing text files when writing.

Otherwise if the edit made the text shorter, the remaining content won't be truncated because ContentResolver.openOutputStream(Uri) defaults to "w" only.

This wasn't a problem until API 29 because previously the platform ParcelFileDescriptor.parseMode() (incorrectly) treated "w" to be the same as "wt" and added MODE_TRUNCATE. However, that has been fixed since API 29, while the default mode for ContentResolver.openOutputStream(Uri) remained "w", which resulted in such a bug.

See also https://stackoverflow.com/q/56902845 .
This commit is contained in:
Hai Zhang
2022-05-01 19:49:05 -07:00
committed by GitHub
parent 57859b425b
commit c3bfb744f6
@@ -84,13 +84,13 @@ public class WriteTextFileCallable implements Callable<Unit> {
DocumentFile documentFile =
DocumentFile.fromSingleUri(AppConfig.getInstance(), fileAbstraction.uri);
if (documentFile != null && documentFile.exists() && documentFile.canWrite()) {
outputStream = contentResolver.openOutputStream(fileAbstraction.uri);
outputStream = contentResolver.openOutputStream(fileAbstraction.uri, "wt");
} else {
destFile = FileUtils.fromContentUri(fileAbstraction.uri);
outputStream = openFile(destFile, context.get());
}
} else {
outputStream = contentResolver.openOutputStream(fileAbstraction.uri);
outputStream = contentResolver.openOutputStream(fileAbstraction.uri, "wt");
}
break;
case FILE: