Search code examples
javaandroidjava-ioandroid-fileandroid-context

Why does FileOutputStream throw FileNotFoundException?


The Android Developer reference (this page) says:

Throws FileNotFoundException

But at the very start, it says:

Open a private file associated with this Context's application package for writing. Creates the file if it doesn't already exist.

If that is the case, why would the FileNotFoundException ever be thrown?

I just want to make sure I'm properly handling all cases. I am using the default functionality, so can I just wrap this in a try..catch block with nothing in the catch block since it is not possible for a FileNotFoundException to ever be thrown in the default functionality?

Edit: example of 'default functionality':

String FILENAME = "hello_file";
String string = "hello world!";
FileOutputStream fos = context.openFileOutput(FILENAME, Context.MODE_PRIVATE);
fos.write(string.getBytes());
fos.close();

Solution

  • This might happen for example if you try to open a Folder or if the file you try to open does not exist, but you don't have permissions to create it either.