java.io.FileNotFoundException in Java

16 Nov, 2021
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:
If the given file is not available in the given location then this error will occur.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.
If the given file is not available in the given location then this error will occur.
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
// Java program to illustrate // FileNotFoundException   // All output and input streams // are available in java.io packageimport java.io.*;  public class Example1 {  public static void main(String[] args)   {             // creating object of FileReader    FileReader reader = new FileReader("file.txt");          // passing FileReader to    // buffered reader    BufferedReader br = new BufferedReader(reader);          // declaring empty string     String data =null;          // while loop to read data     // and printing them    while ((data = br.readLine()) != null)     {        System.out.println(data);    }          // closing the object    br.close();  }}
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
// Java program to illustrate // FileNotFoundException   // All output and input streams // are available in java.io packageimport java.io.*;import java.util.*;  class Example2 {  public static void main(String[] args) {          // starting try block    try {        // Opening the file          File f=new File("file.txt");                         // creating printWriter object          // by initiating fileWriter         PrintWriter p1=new PrintWriter(new FileWriter(f), true);                      // printing sample text        p1.println("Hello world");          p1.close();                  // changing the file operation           // to read-only         f.setReadOnly();                  // trying to write to new file          PrintWriter p2=new PrintWriter(new FileWriter("file.txt"), true);        p2.println("Hello World");    }          // catching exception thrown    // by try block    catch(Exception ex) {        ex.printStackTrace();    }  }}
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:
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.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.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.
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.
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.
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.
anikakapoor
Java-Exceptions
Picked
Technical Scripter 2020
Java
Java Programs
Technical Scripter
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.