[ACCEPTED]-Detect underlying cause for java.io.FileNotFoundException-filenotfoundexception

Accepted answer
Score: 10

Do the check for file existence/read-write 5 permissions yourself before creating FileOutputStream.

File test_csv = new File( "\\server\share\directory\test.csv" );

if ( test_csv.exists( ) && test_csv.canWrite( ) )
{
  // Create file writer
  ...
}
else
{
  // notify user
  ...
}

Notice 4 that sometimes you will have to check the 3 read/write permissions on a parent of you 2 destination file, if you need to create 1 a new file.

File test_csv = new File( "\\server\share\directory\test.csv" );
File parent_dir = test_csv.getParentFile( )

if ( parent_dir.exists( ) && parent_dir.canWrite( ) )
{
  // Create file writer
  ...
}
else
{
  // notify user
  ...
}
Score: 2

You may want to look at the properties of 4 the file using the java.io.File object before attempting 3 to read the file. There's a canRead method 2 on that you can use to determine whether 1 or not the user can read the file.

Score: 1

One approach is to look at the actual type 7 of the exception: as you can see from the 6 docs, there are a lot of subclasses that provide 5 finer-grained information.

However, you probably 4 won't get far with that. As with most checked 3 exceptions, it's usually better to log/report 2 the exception and ask the user for choices 1 on how to correct it.

More Related questions