Skip to content

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. Please see the below-given code example where I try to open a directory and try to read it.

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 this 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 the 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 the below example.

Output

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

Fix:

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

5) File is being used by another process

If the file is already 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 process.

This example is a part of the Java File tutorial.

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

About the author

2 comments

Leave a Reply

Your email address will not be published.