Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to append to a file using android Storage access framework?

How can I use storage access framework to get a FileOutputStream to append to a file? The following code overwrites the file

void write(Uri uri){
        try {
            ParcelFileDescriptor descriptor=getContentResolver().openFileDescriptor(uri,"w");
            if(descriptor!=null) {
                FileOutputStream op=new FileOutputStream(descriptor.getFileDescriptor());
                op.write("test string".getBytes());
                op.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

I know doing it with java.io.File using FileOutputStream(File file,boolean append)

But I can't see FileOutputStream(FileDescriptor fd,boolean append)

like image 216
ajk Avatar asked Feb 06 '26 03:02

ajk


2 Answers

Instead of creating FileOutputStream from

FileOutputStream op = new FileOutputStream(descriptor.getFileDescriptor());

you can directly get OutputStream using

context.getContentResolver().openOutputStream(yourUri, "wa");

and provide this following modes w wa rw or rwt and to append existing file use wa

like image 104
Amanth Rai Avatar answered Feb 07 '26 23:02

Amanth Rai


If you want to append to the file, you need to use access mode "wa" instead of "w" in this call:

ParcelFileDescriptor descriptor =
    getContentResolver().openFileDescriptor(uri, "w");
like image 36
David Wasser Avatar answered Feb 07 '26 21:02

David Wasser



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!