Search code examples
androidstorage-access-framework

How to append file content with SAF without using FileOutputStream


FileOutputStream allows to append a file just setting the append attribute to true in its constructor, unfortunately with SAF FileOutputStream cannot be used due to direct path limitations and file write is something like

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

if I use out.append(somestring);rather than out.print(somestring);the behavior is exactly the same and the content of file is replaced, but I want that new input is appended to existent content of file for each invocation.


Solution

  • There are two forms of openOutputStream(). The one-parameter version that you are using is the equivalent of calling the two-parameter version with a mode of "w". For an append operation, try the two-parameter version with "wa" as the mode:

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

    See the documentation for more.