Ошибка нет доступа к файлу java

I am trying to read the files inside a folder, but when I run the program it throws this exception. I tried with some other folders also. It throws the same exception.

Exception in thread "main" java.io.FileNotFoundException: C:backup (Access is denied)
    at java.io.FileInputStream.open(Native Method)
    at java.io.FileInputStream.<init>(Unknown Source)

Michaël's user avatar

Michaël

3,6817 gold badges39 silver badges64 bronze badges

asked Nov 25, 2010 at 22:03

John's user avatar

You cannot open and read a directory, use the isFile() and isDirectory() methods to distinguish between files and folders. You can get the contents of folders using the list() and listFiles() methods (for filenames and Files respectively) you can also specify a filter that selects a subset of files listed.

answered Nov 25, 2010 at 22:12

rsp's user avatar

rsprsp

23.1k6 gold badges55 silver badges69 bronze badges

0

  1. check the rsp’s reply
  2. check that you have permissions to read the file
  3. check whether the file is not locked by other application. It is relevant mostly if you are on windows. for example I think that you can get the exception if you are trying to read the file while it is opened in notepad

answered Nov 25, 2010 at 22:28

AlexR's user avatar

AlexRAlexR

114k16 gold badges130 silver badges207 bronze badges

1

Also, in some cases is important to check the target folder permissions. To give write permission for the user might be the solution. That worked for me.

answered Nov 10, 2014 at 14:55

Thales Valias's user avatar

Here’s a gotcha that I just discovered — perhaps it might help someone else. If using windows the classes folder must not have encryption enabled! Tomcat doesn’t seem to like that. Right click on the classes folder, select «Properties» and then click the «Advanced…» button. Make sure the «Encrypt contents to secure data» checkbox is cleared. Restart Tomcat.

It worked for me so here’s hoping it helps someone else, too.

answered Jun 4, 2018 at 17:46

Rex the Strange's user avatar

Check the file path properly, usually we mention the location and forget to specify the file name or the exact position where it belongs to.

answered Mar 6, 2021 at 9:25

Shubham Ray's user avatar

Приветствую. Есть файл Input, который создан в документах. Есть программа, которая копирует этот файл в файл Output. Однако при ее выполнение выбрасывается FileNotFoundException и пишет «Отказано в доступе». Пробовал запустить от имени администратора—идея не реагирует вообще никак.
Сама программа:

public void copyFile() {
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));

        System.out.println("Приветствуем! Это приложение для копирования файлов.");

        System.out.println("Введите имя файла и его расширение");
        try {
            path = reader.readLine();
        } catch (IOException e) {
            System.out.println("Такого пути не существует.");
        }

        System.out.println("Введите размер файла(в байтах)");
        try {
            fileSize = reader.read();
        } catch (IOException e) {
            System.out.println("Размер файла некорректный");
        }

        try(FileInputStream input = new FileInputStream(path);
            FileOutputStream output = new FileOutputStream("Output")) {
            if (fileSize < 1024) {
                byte[] bytes = input.readAllBytes();
                output.write(bytes);
            } else {
                byte[] bytes = new byte[fileSize];

                while (input.available() > 0) {
                    int real = input.read(bytes);
                    output.write(bytes, 0, real);
                }

                }

        } catch (FileNotFoundException e) {
            e.printStackTrace();

        } catch (IOException e) {
            e.printStackTrace();
        }

       // System.out.println("Копирование завершено успешно");
    }
}

Что делать?

P. S. Всегда проверяйте ваши пути))

Why do I get this error when I run this program? This occurs after random iterations. Usually after the 8000th iteration.

public static void main(String[] args)
{
    FileWriter writer = null;
    try
    {
        for(int i = 0; i < 10000; i++)
        {
            File file = new File("C:\Users\varun.achar\Desktop\TODO.txt");

            if(file.exists())
            {
                System.out.println("File exists");
            }
            writer = new FileWriter(file, true);
            writer.write(i);
            System.out.println(i);
            writer.close();
            if(!file.delete())
            {
                System.out.println("unable to delete");
            }

            //Thread.sleep(10);
            //writer = null;
            //System.gc();
        }
    }
    catch(IOException e)
    {
        e.printStackTrace();
    }
    finally
    {
        if(writer != null)
        {
            try
            {
                writer.close();
            }
            catch(IOException e)
            {
                e.printStackTrace();
            }
        }
    }
}

After the exception occurs, the file isn’t present. That means the it is deleting, but FIleWriter tries to acquire the lock before that, even though it isn’t a multi threaded program. Is it because the Windows isn’t deleting the file fast enough, and hence the FileWriter doesn’t get a lock? If so, then file.delete() method returns before windows actually deletes it?

How do i resolve it, since i’m getting a similar issue during load testing my application.

EDIT 1: Stacktrace:

java.io.FileNotFoundException: C:Usersvarun.acharDesktopTODO.txt (Access is denied)     
at java.io.FileOutputStream.openAppend(Native Method)
    at java.io.FileOutputStream.<init>(FileOutputStream.java:192)
    at java.io.FileOutputStream.<init>(FileOutputStream.java:116)
    at java.io.FileWriter.<init>(FileWriter.java:61)

EDIT 2 : Added file.exists() and file.delete conditions in the program. and the new stacktrace:

7452
java.io.FileNotFoundException: C:Usersvarun.acharDesktopTODO.txt (Access is denied)
    at java.io.FileOutputStream.openAppend(Native Method)
    at java.io.FileOutputStream.<init>(FileOutputStream.java:192)
    at java.io.FileWriter.<init>(FileWriter.java:90)
    at com.TestClass.main(TestClass.java:25)

EDIT 3 Thread dump

TestClass [Java Application]    
    com.TestClass at localhost:57843    
        Thread [main] (Suspended (exception FileNotFoundException)) 
            FileOutputStream.<init>(File, boolean) line: 192    
            FileWriter.<init>(File, boolean) line: 90   
            TestClass.main(String[]) line: 24   
    C:Usersvarun.acharDocumentsSoftwaresJava JDKJDK 6.26jdkjrebinjavaw.exe (09-Nov-2011 11:57:34 PM)  

EDIT 4 : Program runs successfully on different machine with same OS. Now how do i ensure that the app with run successfully in the machine it is deployed in?

java.io.FileNotFoundException which is a common exception which occurs while we try to access a file. FileNotFoundExcetion is thrown by constructors RandomAccessFile, FileInputStream, and FileOutputStream. FileNotFoundException occurs at runtime so it is a checked exception, we can handle this exception by java code, and we have to take care of the code so that this exception doesn’t occur. 

Declaration : 

public class FileNotFoundException
  extends IOException
    implements ObjectInput, ObjectStreamConstants

Constructors : 

  • FileNotFoundException() : It gives FileNotFoundException with null message.
  • FileNotFoundException(String s) : It gives FileNotFoundException with detail message.

It doesn’t have any methods. Now let’s understand the hierarchy of this class i.e FileNotFoundException extends IOException which further extends the Exception class which extends the Throwable class and further the Object class. 

Hierarchy Diagram:

Why this Exception occurs? 

There are mainly 2 scenarios when FileNotFoundException occurs. Now let’s see them with examples provided:

  1. If the given file is not available in the given location then this error will occur.
  2. If the given file is inaccessible, for example, if it is read-only then you can read the file but not modify the file, if we try to modify it, an error will occur or if the file that you are trying to access for the read/write operation is opened by another program then this error will occur.

Scenario 1:

If the given file is not available in the given location then this error will occur.

Example: 

Java

import java.io.*;

public class Example1 

{

  public static void main(String[] args) 

  {

    FileReader reader = new FileReader("file.txt");

    BufferedReader br = new BufferedReader(reader);

    String data =null;

    while ((data = br.readLine()) != null

    {

        System.out.println(data);

    }

    br.close();

  }

}

Output

prog.java:14: error: unreported exception FileNotFoundException; must be caught or declared to be thrown
    FileReader reader = new FileReader("file.txt");
                        ^
prog.java:25: error: unreported exception IOException; must be caught or declared to be thrown
    while ((data = br.readLine()) != null) 
                              ^
prog.java:31: error: unreported exception IOException; must be caught or declared to be thrown
    br.close();
            ^
3 errors

Scenario 2:

If the given file is inaccessible, for example, if it is read-only then you can read the file but not modify the file if we try to modify it, an error will occur or if the file that you are trying to access for the read/write operation is opened by another program then this error will occur.

Example:

Java

import java.io.*;

import java.util.*;

class Example2 {

  public static void main(String[] args) {

    try {

          File f=new File("file.txt");   

        PrintWriter p1=new PrintWriter(new FileWriter(f), true);

        p1.println("Hello world");

          p1.close();

        f.setReadOnly();

          PrintWriter p2=new PrintWriter(new FileWriter("file.txt"), true);

        p2.println("Hello World");

    }

    catch(Exception ex) {

        ex.printStackTrace();

    }

  }

}

Output

java.security.AccessControlException: access denied ("java.io.FilePermission" "file.txt" "write")
    at java.base/java.security.AccessControlContext.checkPermission(AccessControlContext.java:472)
    at java.base/java.security.AccessController.checkPermission(AccessController.java:897)
    at java.base/java.lang.SecurityManager.checkPermission(SecurityManager.java:322)
    at java.base/java.lang.SecurityManager.checkWrite(SecurityManager.java:752)
    at java.base/java.io.FileOutputStream.<init>(FileOutputStream.java:225)
    at java.base/java.io.FileOutputStream.<init>(FileOutputStream.java:187)
    at java.base/java.io.FileWriter.<init>(FileWriter.java:96)
    at Example2.main(File.java:19)

Handling Exception:

Firstly we have to use the try-catch block if we know whether the error will occur. Inside try block all the lines should be there if there are chances of errors. There are other remedies to handle the exception:

  1. If the message of the exception tells that there is no such file or directory, then you re-verify whether you mentioned the wrong file name in the program or file exists in that directory or not.
  2. If the message of the exception tells us that access is denied then we have to check the permissions of the file (read, write, both read and write) and also check whether that file is in use by another program.
  3. If the message of the exception tells us that the specified file is a directory then you must either delete the existing directory(if the directory not in use) or change the name of the file.

Last Updated :
16 Nov, 2021

Like Article

Save Article

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.

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.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

package com.javacodeexamples.exceptionexamples;

import java.io.File;

import java.io.FileInputStream;

import java.io.FileNotFoundException;

import java.io.IOException;

public class AccessDeniedExample {

    public static void main(String[] args) {

        FileInputStream fis = null;

        try{

            File file = new File(«C:/dir_1»);

            /*

             * Opening and reading a directory!

             */

            fis = new FileInputStream(file);

        }catch(FileNotFoundException fnfe){

            fnfe.printStackTrace();

        }finally{

            try{

                if(fis != null)

                    fis.close();

            }catch(IOException ioe){

                ioe.printStackTrace();

            }

        }

    }

}

Output

java.io.FileNotFoundException: C:dir_1 (Access is denied)

    at java.io.FileInputStream.open(Native Method)

    at java.io.FileInputStream.<init>(Unknown Source)

    at com.javacodeexamples.exceptionexamples.AccessDeniedExample.main(AccessDeniedExample.java:22)

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.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

FileInputStream fis = null;

try{

    //No read permission

    File file = new File(«C:/dir_1/data.txt»);

    fis = new FileInputStream(file);

}catch(FileNotFoundException fnfe){

    fnfe.printStackTrace();

}finally{

    try{

        if(fis != null)

            fis.close();

    }catch(IOException ioe){

        ioe.printStackTrace();

    }

}

Output

java.io.FileNotFoundException: C:dir_1data.txt (Access is denied)

    at java.io.FileInputStream.open(Native Method)

    at java.io.FileInputStream.<init>(Unknown Source)

    at com.javacodeexamples.exceptionexamples.AccessDeniedExample.main(AccessDeniedExample.java:54)

Fix:

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

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

FileInputStream fis = null;

try{

    //No read permission

    File file = new File(«C:/dir_1/data.txt»);

    if(!file.canRead())

        file.setReadable(true);

    fis = new FileInputStream(file);

}catch(FileNotFoundException fnfe){

    fnfe.printStackTrace();

}finally{

    try{

        if(fis != null)

            fis.close();

    }catch(IOException ioe){

        ioe.printStackTrace();

    }

}

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.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

package com.javacodeexamples.exceptionexamples;

import java.io.File;

import java.io.FileNotFoundException;

import java.io.FileOutputStream;

import java.io.IOException;

public class AccessDeniedExample {

    public static void main(String[] args) throws IOException {

        FileOutputStream fos = null;

        try{

            //read only file with same name already exists

            File file = new File(«C:/dir_1/data.txt»);

            /*

             * Trying to overwrite a read only file!

             */

            fos = new FileOutputStream(file);

        }catch(FileNotFoundException fnfe){

            fnfe.printStackTrace();

        }finally{

            try{

                if(fos != null)

                    fos.close();

            }catch(IOException ioe){

                ioe.printStackTrace();

            }

        }        

    }

}

Output

java.io.FileNotFoundException: C:dir_1data.txt (Access is denied)

    at java.io.FileOutputStream.open(Native Method)

    at java.io.FileOutputStream.<init>(Unknown Source)

    at java.io.FileOutputStream.<init>(Unknown Source)

    at com.javacodeexamples.exceptionexamples.AccessDeniedExample.main(AccessDeniedExample.java:37)

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.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

package com.javacodeexamples.exceptionexamples;

import java.io.File;

import java.io.FileNotFoundException;

import java.io.FileOutputStream;

import java.io.IOException;

public class AccessDeniedExample {

    public static void main(String[] args) throws IOException {

        FileOutputStream fos = null;

        try{

            //read only file with same name already exists

            File file = new File(«C:/dir_1/data.txt»);

            /*

             * Make sure that if the file exists, it is writable first

             */

            if(file.exists() && !file.canWrite()){

                System.out.println(«File exists and it is read only, making it writable»);

                file.setWritable(true);

            }

            fos = new FileOutputStream(file);

            System.out.println(«File can be overwritten now!»);

        }catch(FileNotFoundException fnfe){

            fnfe.printStackTrace();

        }finally{

            try{

                if(fos != null)

                    fos.close();

            }catch(IOException ioe){

                ioe.printStackTrace();

            }

        }        

    }

}

Output

File exists and it is read only, making it writable

File can be overwritten now!

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

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

FileOutputStream fos = null;

try{

    /*

     * Trying to write a file in root folder

     * of the windows system drive.

     */

    File file = new File(«C:/data.txt»);    

    fos = new FileOutputStream(file);

}catch(FileNotFoundException fnfe){

    fnfe.printStackTrace();

}finally{

    try{

        if(fos != null)

            fos.close();

    }catch(IOException ioe){

        ioe.printStackTrace();

    }

}

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

  • Author
  • Recent Posts

Rahim

I have a master’s degree in computer science and over 18 years of experience designing and developing Java applications. I have worked with many fortune 500 companies as an eCommerce Architect. Follow me on LinkedIn and Facebook.

Понравилась статья? Поделить с друзьями:
  • Ошибка нет доступа к файлу c windows
  • Ошибка нет доступа к удаленному серверу
  • Ошибка нет доступа к таблице postgresql
  • Ошибка нет доступа к съемному жесткому диску
  • Ошибка нет доступа к сети или доступ ограничен