I know there are a number of posts here on the java.io.IOException: write failed: EBADF (Bad file number)
exception, but non of them seems to answer my particular question:
Suppose my activity is called with Intent.ACTION_VIEW
and I got a Uri
via Uri uri = intent.getData()
that starts with content://
from which I read some data (for example a pdf file). Now I want to find out whether I can also write to that Uri
to decide whether a "save" button should be shown to the user, or just a "save as" button.
Suppose further that I can successfully open first a ParcelFileDescriptor
and finally a FileOutputStream
as in
ParcelFileDescriptor pfd = context.getContentResolver().openFileDescriptor(uri, "w");
FileOutputStream fileOutputStream = new FileOutputStream(pfd.getFileDescriptor());
such that fileOutputStream != null
.
Depending on the Uri
it can now happen that if I try to write to fileOutputStream
I get the exception:
Exception=java.io.IOException: write failed: EBADF (Bad file number)
I would like to know in advance whether this will happen without actually touching/changing the file. One would think that it should be possible to find out whether I can write to a given Uri
or not before trying.
How can I achieve that?
Additional observations:
I suppose that the above happens when I don't have permission to write to that particular file/uri, but then why does Android let me open a FileOutputStream
in the first place?
For testing I use attachments in emails received with Kaiten mail on an ICS device. If I my app opens after I click on "save" in Kaiten mail uri
matches content://media/external/file/[0-9]*
and everything works, if I however clicked on "open" uri
matches content://com.kaitenmail.attachmentprovider/[-0-9a-f]*/[0-9]*/VIEW
and I run into the above error.
public static StructStat android.system.Os#fstat(FileDescriptor fd)
? i know its API 21... – PenicillinFile#canWrite()
? you would need to convert yourUri
toFile
though... – Penicillinpfd
object. Or else it's an Android bug. – BrinnFile
from aUri
that starts withcontent://
or am I missing something`? @EJP: I want to know whether I can write to the file without modifying it. However, I only get the exception after trying to write to. – Barreracontent://
you cannot do that... – PenicillinContentResolver#openOutputStream(Uri uri)
directly and see if it returns null / throws an exception ? – PenicillinOutputStream
and the same exception when I try to write to it. – BarreraContext#checkCallingUriPermission (Uri uri, int modeFlags)
orContext#checkCallingOrSelfUriPermission (Uri uri, int modeFlags)
– PenicillinPERMISSION_DENIED
) when called withmodeFlages=Intent.FLAG_GRANT_WRITE_URI_PERMISSION
on the givenuri
. Unfortunately they also do so for uris/files to which I can successfully write without the above exception appearing. – Barrera