The only truly safe way to deal with missing files is to eliminate the exception. Consider this:
if (file.exists() && file.canRead()) { try { is = new FileInputStream(file); } catch (IOException ex) {
In fact, the “never happens” CAN case may occur. For instance:
If file is actually a directory, then open will fail. (You can handle this by calling file.isDirectory() , but there are other cases that are difficult to handle ... for example, creating a file on removable removable media.)
Suppose an external application deletes a file or changes its permissions in a tiny window between this application that checks the file and tries to open it. There is simply no way to deal with this race condition ...
In addition, each of these tests is probably a system call. System calls are expensive - about as expensive as creating / throwing / catching exceptions.
Thus, the best way to deal with the possibility of IO exceptions when opening a file is to YEAR THEM FOR YEARS. By all means, use the API file to help diagnose the problem, but don't rely on it to avoid an IO exception.
source share