Ошибка java io filenotfoundexception

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

Put the word.txt directly as a child of the project root folder and a peer of src

Project_Root
    src
    word.txt

Disclaimer: I’d like to explain why this works for this particular case and why it may not work for others.

Why it works:

When you use File or any of the other FileXxx variants, you are looking for a file on the file system relative to the «working directory». The working directory, can be described as this:

When you run from the command line

C:EclipseWorkspaceProjectRootbin > java com.mypackage.Hangman1

the working directory is C:EclipseWorkspaceProjectRootbin. With your IDE (at least all the ones I’ve worked with), the working directory is the ProjectRoot. So when the file is in the ProjectRoot, then using just the file name as the relative path is valid, because it is at the root of the working directory.

Similarly, if this was your project structure ProjectRootsrcword.txt, then the path "src/word.txt" would be valid.

Why it May not Work

For one, the working directory could always change. For instance, running the code from the command line like in the example above, the working directory is the bin. So in this case it will fail, as there is not binword.txt

Secondly, if you were to export this project into a jar, and the file was configured to be included in the jar, it would also fail, as the path will no longer be valid either.

That being said, you need to determine if the file is to be an embedded-resource (or just «resource» — terms which sometimes I’ll use interchangeably). If so, then you will want to build the file into the classpath, and access it via an URL. First thing you would need to do (in this particular) case is make sure that the file get built into the classpath. With the file in the project root, you must configure the build to include the file. But if you put the file in the src or in some directory below, then the default build should put it into the class path.

You can access classpath resource in a number of ways. You can make use of the Class class, which has getResourceXxx method, from which you use to obtain classpath resources.

For example, if you changed your project structure to ProjectRootsrcresourcesword.txt, you could use this:

InputStream is = Hangman1.class.getResourceAsStream("/resources/word.txt");
BufferedReader reader = new BufferedReader(new InputStreamReader(is));

getResourceAsStream returns an InputStream, but obtains an URL under the hood. Alternatively, you could get an URL if that’s what you need. getResource() will return an URL

For Maven users, where the directory structure is like src/main/resources, the contents of the resources folder is put at the root of the classpath. So if you have a file in there, then you would only use getResourceAsStream("/thefile.txt")

The java.io.FileNotFoundException is a checked exception in Java that occurs when an attempt to open a file denoted by a specified pathname fails. This exception is thrown by the FileInputStream, FileOutputStream, and RandomAccessFile constructors when a file with the specified pathname either does not exist or is inaccessible.

Since FileNotFoundException is a checked exception, it must be explicitly handled in methods which can throw this exception — either by using a try-catch block or by throwing it using the throws clause.

What Causes FileNotFoundException

There are two main scenarios when the FileNotFoundException occurs:

  • If a file with the specified pathname does not exist.
  • If a file with the specified pathname is inaccessible, for example, if the file is read-only and is attempted to be opened for writing.

FileNotFoundException Example

Here’s an example of a FileNotFoundException thrown when trying to access a file that does not exist in the system:

public class FileNotFoundExceptionExample {
    public static void main(String args[]) {
        BufferedReader br = null;

        try {
            br = new BufferedReader(new FileReader("myfile.txt"));
            String data = null;

            while ((data = br.readLine()) != null) {
                System.out.println(data);
            }
        } catch (IOException ioe) {
            ioe.printStackTrace();
        } finally {
            try {
                if (br != null) {
                    br.close();
                }
            } catch (IOException ioe) {
                ioe.printStackTrace();
            }
        }
    }
}

In the above example, a file with the name myfile.txt is attempted to be accessed. However, since no such file exists in the system, a FileNotFoundException is thrown:

java.io.FileNotFoundException: myfile.txt (No such file or directory)
    at java.base/java.io.FileInputStream.open0(Native Method)
    at java.base/java.io.FileInputStream.open(FileInputStream.java:212)
    at java.base/java.io.FileInputStream.<init>(FileInputStream.java:154)
    at java.base/java.io.FileInputStream.<init>(FileInputStream.java:109)
    at java.base/java.io.FileReader.<init>(FileReader.java:60)
    at FileNotFoundExceptionExample.main(FileNotFoundExceptionExample.java:10)

How to Fix FileNotFoundException

Since FileNotFoundException is a checked exception, a try-catch block should be used to handle it. The try block should contain the lines of code that can throw the exception and the catch block should catch and handle the exception appropriately.

Some ways to fix the exception are:

  • If the message of the exception indicates that no such file or directory exists, the file pathname should be checked again to ensure it is correct and if the file exists at the specified location.
  • If the message indicates that access is denied, the permissions of the file should be verified and whether the file is in use by another program.
  • If the message indicates that the specified file is a directory, the name of the file should be changed or the existing directory should be deleted if not in use.

Track, Analyze and Manage Errors With Rollbar

Managing errors and exceptions in your code is challenging. It can make deploying production code an unnerving experience. Being able to track, analyze, and manage errors in real-time can help you to proceed with more confidence. Rollbar automates error monitoring and triaging, making fixing Java errors easier than ever. Sign Up Today!

In this tutorial, we will discuss how to solve the java.io.FileNotFoundException – FileNotFoundException in Java. This exception is thrown during a failed attempt to open the file denoted by a specified pathname.

Also, this exception can be thrown when an application tries to open a file for writing, but the file is read-only, or the permissions of the file do not allow the file to be read by any application.

You can also check this tutorial in the following video:

java.io.FileNotFoundException – Video

This exception extends the IOException class, which is the general class of exceptions produced by failed or interrupted I/O operations. Also, it implements the Serializable interface and finally, the FileNotFoundException exists since the first version of Java (1.0).

java.io.FileNotFoundException

The following constructors throw a FileNotFoundException when the specified filename does not exist: FileInputStream, FileOutputStream, and RandomAccessFile. These classes aim to obtain input bytes from a file in a file system, while the former class supports both reading and writing to a random access file.

The following snippet reads all the lines of a file, but if the file does not exist, a java.io.FileNotFoundException is thrown.

FileNotFoundExceptionExample.java

01

02

03

04

05

06

07

08

09

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

import java.io.BufferedReader;

import java.io.File;

import java.io.FileReader;

import java.io.IOException;

public class FileNotFoundExceptionExample {

    private static final String filename = "input.txt";

    public static void main(String[] args) {

        BufferedReader rd = null;

        try {

            rd = new BufferedReader(new FileReader(new File(filename)));

            String inputLine = null;

            while((inputLine = rd.readLine()) != null)

                System.out.println(inputLine);

        }

        catch(IOException ex) {

            System.err.println("An IOException was caught!");

            ex.printStackTrace();

        }

        finally {

            try {

                rd.close();

            }

            catch (IOException ex) {

                System.err.println("An IOException was caught!");

                ex.printStackTrace();

            }

        }

    }

}

In case the file is missing, the following output is produced:

An IOException was caught!
java.io.FileNotFoundException: input.txt (No such file or directory)
	at java.io.FileInputStream.open(Native Method)
	at java.io.FileInputStream.(FileInputStream.java:146)
	at java.io.FileReader.(FileReader.java:72)
	at main.java.FileNotFoundExceptionExample.main(FileNotFoundExceptionExample.java:16)
Exception in thread "main" java.lang.NullPointerException
	at main.java.FileNotFoundExceptionExample.main(FileNotFoundExceptionExample.java:30)

The following snippet tries to append a string at the end of a file. If the file does not exist, the application creates it. However, if the file cannot be created, is a directory, or the file already exists but its permissions are sufficient for changing its content, a FileNotFoundException is thrown.

FileNotFoundExceptionExample_v2.java

01

02

03

04

05

06

07

08

09

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

import java.io.BufferedWriter;

import java.io.File;

import java.io.FileWriter;

import java.io.IOException;

public class FileNotFoundExceptionExample_v2 {

    private static final String filename = "input.txt";

    public static void main(String[] args) {

        BufferedWriter wr = null;

        try {

            wr = new BufferedWriter(new FileWriter(new File(filename), true));

            wr.write("A sample string to be written at the end of the file!n");

        }

        catch(IOException ex) {

            System.err.println("An IOException was caught!");

            ex.printStackTrace();

        }

        finally {

            try {

                wr.close();

            }

            catch (IOException ex) {

                System.err.println("An IOException was caught!");

                ex.printStackTrace();

            }

        }

    }

}

If the file exists and is a directory, the following exception is thrown:

An IOException was caught!
java.io.FileNotFoundException: input.txt (Is a directory)
	at java.io.FileOutputStream.open(Native Method)
	at java.io.FileOutputStream.(FileOutputStream.java:221)
	at java.io.FileWriter.(FileWriter.java:107)
	at main.java.FileNotFoundExceptionExample_v2.main(FileNotFoundExceptionExample_v2.java:16)
Exception in thread "main" java.lang.NullPointerException
	at main.java.FileNotFoundExceptionExample_v2.main(FileNotFoundExceptionExample_v2.java:28)

If the file exists, but it doesn’t have the appropriate permissions for writing, the following exception is thrown:

An IOException was caught!
java.io.FileNotFoundException: input.txt (Permission denied)
	at java.io.FileOutputStream.open(Native Method)
	at java.io.FileOutputStream.(FileOutputStream.java:221)
	at java.io.FileWriter.(FileWriter.java:107)
	at main.java.FileNotFoundExceptionExample_v2.main(FileNotFoundExceptionExample_v2.java:16)
Exception in thread "main" java.lang.NullPointerException
	at main.java.FileNotFoundExceptionExample_v2.main(FileNotFoundExceptionExample_v2.java:28)

Finally, the aforementioned exception can occur when the requested file exists, but it is already opened by another application.

2. How to deal with the java.io.filenotfoundexception

  • If the message of the exception claims that there is no such file or directory, then you must verify that the specified is correct and actually points to a file or directory that exists in your system.
  • If the message of the exception claims that permission is denied then, you must first check if the permissions of the file are correct and second, if the file is currently being used by another application.
  • If the message of the exception claims that the specified file is a directory, then you must either alter the name of the file or delete the existing directory (if the directory is not being used by an application).

Important: For those developers that use an IDE to implement their Java applications, the relative path for every file must be specified starting from the level where the src directory of the project resides.

3. Download the Eclipse Project

This was a tutorial about the FileNotFoundException in Java.

Last updated on Oct. 12th, 2021

Photo of Sotirios-Efstathios Maneas

Sotirios-Efstathios (Stathis) Maneas is a PhD student at the Department of Computer Science at the University of Toronto. His main interests include distributed systems, storage systems, file systems, and operating systems.

FileNotFoundException In Java: In this article, we’re going to talk about a very common exception in Java – the FileNotFoundException. we can get this exception when we try to access the file but the file is not present in that location,

Possible Reasons For FileNotFound Exception

There are a few possible reasons for getting this type of exception, here are some:

  • A File may be present or not in the mentioned path
  • A file with the specified pathname does exist but is inaccessible for some reason (requested writing for a read-only file, or permissions don’t allow accessing the file)

FileNotFoundException in Java

This exception will be thrown by the FileInputStream, FileOutputStream, and RandomAccessFile constructors when a file with the specified pathname does not exist. It will also be thrown by these constructors if the file does exist but for some reason is inaccessible, for example when an attempt is made to open a read-only file for writing.

Check Also: Scientific Games Interview Questions

we will get this exception when we are trying to access a file that does not exist. for access to the files, we are using classes like  FileInputStream, FileOutputStream, and RandomAccessFile. The main function of these classes is used to obtain the bytes from a file system.

package co.java.exception;
import java.io.File;
import java.io.FileReader;
public class FileNotFoundException 
{
   @SuppressWarnings("unused")
   public static void main(String[] args) throws java.io.FileNotFoundException
   {
      File file = new File("E://file.txt");
        @SuppressWarnings("resource")
      FileReader fr = new FileReader(file);
   }
}

Let’s Run the above program

After execution we get an error:

Exception in thread "main" java.io.FileNotFoundException: E:file.txt (The system cannot find the file specified)
at java.io.FileInputStream.open0(Native Method)
at java.io.FileInputStream.open(Unknown Source)
at java.io.FileInputStream.&lt;init&gt;(Unknown Source)
at java.io.FileReader.&lt;init&gt;(Unknown Source)
at co.java.exception.FileNotFoundException.main(FileNotFoundException.java:12)

How to Deal FileNotFound Exception

  • Once you got this exception than the first thing you need to check the path which you mentioned in your program to verify that the specified file is present or not in the mentioned path.
  • if the file is present in the specified location but still you got the error then you need to check error message for confirming is there any mention about permission related issues if there are some permission related issues then you need to fix that issue or you need to verify that file is used by other application or not.
  • Alert a user with a dialogue or error message: this isn’t a stop execution error, so just notifying is enough
  • Just log an error: this error should not stop the execution but you log it for future analysis

Conclusion

in this post, we’ve seen when a FileNotFoundException can occur and several options to handle it. if still, you have any doubts then feel free to drop your question in the comment section.

Reader Interactions

  • Ошибка java failed to validate certificate the application will not be executed
  • Ошибка java class interface or enum expected
  • Ошибка java application blocked by java security
  • Ошибка java 1723 при удалении
  • Ошибка jam4211 kyocera 2040