Search code examples
javaandroidstorage-access-framework

using Storage Access Framework


It works fine if you write a few data. But if you write a lot of data (which will run for a long time), it will fail with: java.io.IOException: write failed: EBADF (Bad file number)

Here's the code:

writeLargeDataToStream(new FileOutputStream(getContentResolver()
        .openFileDescriptor(data.getData(), "w").getFileDescriptor()));

Solution

  • It seems you need to keep the ParcelFileDescriptor alive from garbage collection by putting it into a local field like this:

    private ParcelFileDescriptor descriptor;
    

    And do this:

    descriptor = getContentResolver().openFileDescriptor(data.getData(), "w");
    writeLargeDataToStream(new FileOutputStream(descriptor.getFileDescriptor()));
    

    When you've done using that, let garbage collector know it's collectible by using:

    descriptor = null;