Vic
Vic

Reputation: 6037

openFileOutput FileNotFoundException

This is my noob question for the week. I'm looking more for general speculation than specific code and maybe hoping the Android folks are watching and could correct this:

the SDK documentation for Context.openFileOutput says:

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

Ok, that sounds good. I can create a file. Except this method also throws a FileNotFoundException, so apparently something is amiss. Why would a function that is supposed to create a file if it's not found throw an exception if the file is not found???

Kinda defeats that whole "Creates the file..." thing, doesn't it?

Upvotes: 26

Views: 7013

Answers (4)

Jay
Jay

Reputation: 141

Possibly also thrown if you use MODE_APPEND, which appends to an existing file and the file doesn't exist.

Upvotes: 1

Vic
Vic

Reputation: 6037

I have to apologize for leaping before I looked on this one. I kinda panicked while reading the documentation. After some testing, I found that openFileOutput() does, in fact, work as advertised and will create a file if it's not found, not just throw an FnF exception as I feared. Apparently, the FnF throw was added in case the Activity's application directory does not exist.

Again, my apologies but hopefully, this might help others who are confused by the documentation.

Upvotes: 29

f20k
f20k

Reputation: 3106

FileNotFoundException is an exception thrown in case that you are trying to write to a file that does not exist, or cannot be currently accessed. When else would this occur?

  • Perhaps you forgot to close the file, and tried to open the same file.
  • Perhaps you tried to create multiple FileOutputStream objects pointing to the same file.

These will result in a FileNotFoundException.

Anyway, you can insert a throws FileNotFoundException at the end of your function declaration where you call openFileOutput (and to other functions that call this function).

Upvotes: 1

Rafael T
Rafael T

Reputation: 15689

Have you inserted the right Permission? see http://developer.android.com/reference/android/Manifest.permission.html for reference. i think

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

could be the one You are fine with

Upvotes: -4

Related Questions