Java Exceptions Java IO

java.io.FileNotFoundException (Access is denied) – Causes and Fix

java.io.FileNotFoundException (Access is denied) – Causes and Fix tutorial shows what are the possible causes and fix for java.io.FileNotFoundException (Access is denied) exception.

How to fix java.io.FileNotFoundException (Access is denied) exception?

There are several possible causes due to which you may encounter java.io.FileNotFoundException (Access is denied) exception as given below.

1) Trying to open and read a directory

You cannot open and read a directory like normal files. Trying to do that will result in the exception.

Output

Fix:

Make sure that you are not trying to open a directory for reading or writing.

2) You do not have permission to read the file

If you try to open and read a file for which you do not have the read permission, you will get the exception.

Output

Fix:

Make sure you have permission to read the file before opening and reading it.

3) Trying to overwrite a read only file

If you try to overwrite a read only file either using stream or writer, you will get the “Access is denied” exception.

Output

Fix:

Always check that if the file with same name exists and it is not read only before actually writing the file. If the file exists and it is read only, make it writable as given in below example.

Output

4) Trying to create a file in root folder of the system drive in Windows

Fix:

In some version of Windows, system does not allow some users to write to the root of the system drive if they do not have required privileges. Try to create a file in subfolder, for example C:/somedir/somefile.txt instead of the root.

5) File is being used by another process

If the file is being opened exclusively by some other process, opening it for either reading or writing will cause java.io.FileNotFoundException (Access is denied) exception.

Fix:

Make sure that the file is not opened by any other program or processes.

Please let us know your views in the comments section below.

Tags
Join 1000+ fellow learners! Enter your email address below: