×

Java IO file not found exception

One of the exception classes offered by the java.io package is FileNotFoundException. An exception is raised when we attempt to access a file that isn't present in the system. It is a checked exception because it is raised by one of the following constructors and happens at run time rather than at compile time:

  • Fileinputstream
  • Randomaccessfile
  • Fileoutputstream

Constructor of FileNotFoundException

There are two types of constructors in FileNotFoundException class. That is:

  • FileNotFoundException () (default constructor)

Due to the lack of a function Object () { [native code] } parameter, it creates a FileNotFoundException and sets the error detail message to null.

The syntax for using this type of constructor

public FileNotFoundException ()
  • FileNotFoundException (String s)

As we supply str to the function Object () { [native code] }, it creates a FileNotFoundException and sets the error detail message.

The syntax for using this type of constructor

public FileNotFoundException (String s)

Methods of FileNotFoundException class

Because it is a subclass of both java.lang.Throwable and java.lang.Object, it offers every method that is provided by those types.

Methods in java.lang.ThrowableMethods in java.lang.Object
addSuppressed ()clone ()
fillInStackTrace ()equals ()
getCause ()finalize ()
getLocalizedMessage ()getClass ()
getMessage ()hashCode ()
getStackTrace ()notify ()
getSuppressed ()notifyAll ()
initCause ()wait ()
printStackTrace () 
setStackTrace () 
toString () 

Why does FileNotFoundException occur

There are primarily two causes for this mistake. The following are the justifications for receiving this exception:

  • When we attempt to access that file, the system does not have it.
  • An error may be raised when we attempt to access a file that isn't available, such as when we try to alter a read-only file.

FileNotFoundExcep.java

// all the required packages are imported  
import java.io.*;   // io class for handling input stream and output stream  
// Class FileNotFoundExcep main class creation.  
public class FileNotFoundExcep   
{  
    public static void main (String[] args)   
    {  
         // object creation for file reader class  
         FileReader fr = new FileReader("Exp.txt");  
         // object creation for buffered reader class and sending fr file reader as the parameter.  
         BufferedReader br = new BufferedReader(fr);  
         // Declaring varible data for storing the file data  
         String data = null;  
         // reading the data in the file using the readLine method of br till the last line   
         while ((data = br.readLine()) != null)   
         {  
             System.out.println(data);  
         }  
         // closing the br object created for bufferreader class  
         try {  
            br.close();  
        } catch (IOException e) {  
            e.printStackTrace();  
        }  
    }  
}  S

Output

Java io filenotfoundexception

FileNotFoundExcep1.java

// all the required packages are imported  
import java.io.*;   
// io class for handling input stream and output stream  
// Class FileNotFoundExcep main class creation.    
public class FileNotFoundExceptionExample2   
{   
    public static void main (String[] args)   
    {  
        try {  
            // object creation for file class as to open the file   
            File obj = new File("Exp.txt");  
            // object creation for print writer class   
            PrintWriter PW = new PrintWriter(new FileWriter(obj), true);  
            // printing the simple print line   
            PW.println("Simple print");  
            PW.close();    
            obj.setReadOnly();  
            // inserting the data into a new file 
            PrintWriter pw1 = new PrintWriter(new FileWriter("Exp.txt"), true);  
            pw1.println("Simple print");  
            pw1.close();  
        }  
        catch (Exception ex) {  
            ex.printStackTrace();  
        }  
    }  
}  

Output

Java io filenotfoundexception

Handling Exceptions

Use of the try-catch block is required to handle the exception. We will place the code line that potentially raises an exception in the try block. The catch block will take care of any exception that arises. The following additional methods are available for removing the FileNotFoundException:

  • Suppose the error message states that the requested file or directory does not exist. In that case, the exception can be removed by re-verifying the program and determining whether the requested file is in the requested location.
  • If we see the error code access is restricted, we must determine whether or not the file's permissions meet our requirements. The file's license must be changed if it does not meet our needs.
  • We must also determine whether or not another software is using the file before we can resolve the access denied problem message.
  • If the error message states that the selected file is a folder, we must either delete it or alter its name.

FileNotFound.java

// all the required packages are imported   
import java.io.*;   
// io class for handling input stream and output stream  
// Class FileNotFound main class creation.    
public class FileNotFound   
{  
    public static void main(String[] args)   
    {  
         // object creation for file reader class  
           
         try {  
                FileReader fr = new FileReader("Exp.txt");  
                // object creation for buffered reader class and sending fr file reader as the parameter. 
                BufferedReader br = new BufferedReader(fr);  
                // Declaring varible data for storing the file data    
                String fileData = null;  
                // reading the data in the file using the readLine method of br till the last line 
                try {  
                    while ((fileData = br.readLine()) != null)   
                    {  
                        System.out.println(fileData);  
                    }  
                } catch (IOException e) {       
                    e.printStackTrace();  
                }  
         } catch (FileNotFoundException ex) {    
            ex.printStackTrace();  
        }  
    }  
}  

Output

Simple print

Related Topics

How to enable java in chrome

The Java module is huge for the Java Runtime Environment (JRE). It permits a program to work with the Java stage to run Java applets. Essentially, each of the undertakings connect...

3 minutes read.

Kotlin Vs Java

Kotlin Vs Java There are many languages available for Android development. Java is the official language for android development but Kotlin is becoming popular nowadays. This article discusses both of these...

4 minutes read.

Java Integer sum() method

The sum() method of Java Integer class add the two specified integers values. It returns the same result as given by + operator. Syntax public static int sum (int a, int b)  Parameters The...

1 minute read.

Java List Implementations

ArrayList and LinkedList are the two implementations of List that are for general-purpose. You'll probably utilise an array list the majority of the time because it's quick and provides constant-time...

3 minutes read.

Producer consumer problem in Java using Synchronised block

The producer-consumer problem in Java, commonly known as the bounded-buffer problem, is a well-known multi-process synchronization challenge where we attempt to synchronize many processes. Two processes are involved in the producer-consumer problem:...

3 minutes read.

Equilibrium Index of an Array in Java

An array's equilibrium index is the condition where the sum of items with lower and higher indices equals. For example, an array A=[-4,5 2,6,-5] where: a[0]=-4, a[1]=5, a[2]=2, a[3]=6, a[4]=-5 Now according...

4 minutes read.

How to open the Java control panel

The many methods for launching the Java control panel will be covered in this section. We will also go through how the Java Control Panel can be used. Java Control Panel The...

2 minutes read.

Various operations on HashSet in Java

In this article, you will be acknowledged about what is a HashSet in java and what are its operations in java programming language. The HashSet is a crucial part of...

3 minutes read.

Use Of Adapter class in Java

An adapter class in Java enables listener interfaces to be implemented by default. The Delegation Event Model is where the idea of listener interfaces first appeared. It is one of...

3 minutes read.

Java Math toIntExact() Method

The toIntExact() method of Java Math class returns the int value of the given long argument, throwing an exception if the value overflows an int. Syntax: public static int toIntExact (long value) Parameters: The...

2 minutes read.

Segment Tree in Java

Binary trees can address a variety of issues; however, the Segment Tree is more efficient in terms of time complexity. The segment tree in Java is represented using an array. Native...

4 minutes read.

Enterprise Java Beans

One of the many Java APIs for the common development of corporate software is Enterprise Java Beans (EJB). An EJB, a server-side software component, contains the business logic of an...

4 minutes read.

File Operation in Java

In Java, a file is an Abstract data type. These are used to store the data which is related. Files are named storage locations. With a file we can perform...

7 minutes read.

Java Control Statements

Control Statements: Control statements in Java can also be referred to as decision-making while dealing with different problems. Control statements are helpful to sort out the flow of the program or...

7 minutes read.

Java Math nextDown() Method

The nextDown() method of Math class returns the floating-point number adjacent to the argument in direction of the negative infinity. Syntax: public static double nextDown (double d)public static float nextDown (float f) Parameters: The...

2 minutes read.

How to Convert Date to String in Java

How to Convert Date to String in Java We need to convert Date to String in Java may for displaying purpose. We can convert Date to String in Java using the format() method of java.text.DateFormat class. There...

2 minutes read.

Binary Search Java

Binary search is a search mechanism for key elements from the given List/Array. In Binary search, the search mechanism is followed by dividing the array into parts; hence the search...

3 minutes read.

Annotations in Java

Annotations in Java Java Annotations are metadata about the source code. They do not have any direct effect on the execution of the java program. Annotations in Java were introduced in...

4 minutes read.

Java Boolean equals() method

The equals() method of Java Boolean class returns a Boolean value true if the specified argument is not null and is same as this object, else it returns false. Syntax public boolean...

2 minutes read.

How to run java program in ubuntu

To run the java programming in ubuntu, we need to follow several steps: Let's see the process. Step1: Install the Java compiler or JDK to the system. To run the java program, we...

3 minutes read.