// Why don't we go in this if ?
The most likely reason (IMO) is that openFileOutput(name, MODE_WORLD_READABLE)
throws an exception.
If that happens, you won't know about it because of this appalling piece of code.
} catch (Exception e) {
// TODO: handle exception
}
Why appalling?
- You are catching
Exception
rather than the specific exceptions that you expect to be thrown (e.g. IOException
).
- You are "squashing" the exception. You are catching it and silently throwing it away.
Each of those things individually is bad practice. Doing them together is ... well ... you deserve to have wasted an hour on this!
If my diagnosis of a squashed exception is incorrect, then there's another possibility. The docs for openFileOutput
say:
"Open a private file associated with this Context's application package for writing.".
It is not entirely clear where that file would be opened / created, but it is plausible that it is in a different "place" to where File.exists
is looking. You will notice that openFileOutput
does NOT take a File
object as its output.
Finally, there is also a more subtle problem, that won't hurt you in this context, but could in others. You wrote ...
if (!fichier.exists()) {
System.out.println("File doesn't exists");
}
FileOutputStream fOut = openFileOutput(name, MODE_WORLD_READABLE);
The problem with this is that there is a race condition. In between calling exists
and calling openFileOutput
, there is a small time window in which some other application could leap in and create the file. So when you then call openFileOutput
, it might discover that the file has already been created.
Clearly, in this case it makes no difference. But in other cases it might. The lesson is that calling File.exists()
, File.canWrite
and so on to "guard" a following attempt to create / open a file is not reliable.