Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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();
like image 455
1owk3y Avatar asked Nov 23 '13 12:11

1owk3y


People also ask

How do I fix FileNotFoundException?

How to Fix FileNotFoundException. Since FileNotFoundException is a checked exception, a try-catch block should be used to handle it. The try block should contain the lines of code that can throw the exception and the catch block should catch and handle the exception appropriately.

How do I handle java io FileNotFoundException?

FileNotFoundException occurs at runtime so it is a checked exception, we can handle this exception by java code, and we have to take care of the code so that this exception doesn't occur. Constructors : FileNotFoundException() : It gives FileNotFoundException with null message.

Why do we use FileNotFoundException?

FileNotFoundException is another exception class available in the java.io package. The exception occurs when we try to access that file which is not available in the system. It is a checked exception because it occurs at run time, not compile-time, and it is thrown by one of the following constructors: RandomAccessFile.

What is difference between Outputstream and FileOutputStream?

Outputstream is an abstract class whereas FileOutputStream is the child class. It's possible that you could use Outputstream to just write in bytes for a prexisting file instead of outputting a file.


1 Answers

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.

like image 57
Blub Avatar answered Oct 13 '22 00:10

Blub