×

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

Thread Safety and How to Achieve it in Java

Before diving into the topic, let’s just recap the concept of Multithreading provided by Java where we can create and execute multiple threads of the same object. When these multiple...

5 minutes read.

String Handling Method in Java

What is a String? Strings are a bundle of different characters that are normally used in Java programming language. Strings are regarded as objects in the Java programming language. “String” is a...

4 minutes read.

Relatively Prime in Java

In this article, you will be very well equipped with a knowledge of a relatively prime number and also Java programs to determine whether a given integer is a relatively...

4 minutes read.

How to find the length of an Array in Java

Arrays: An array is a sort of container object that stores constant quantities of values of a single type in one memory area. A finite number of items must all be...

3 minutes read.

Default Virtual Behaviour in C++ vs Java

Virtual Behaviour in C++: The class member methods in C++ are, by default, non-virtual. This implies that by simply defining it, they can be turned into virtual. The virtual class can be...

3 minutes read.

Davis Staircase Problem in Java

Davis has several stairs in his home and prefers to ascend one, two, or three steps at a time. As a highly clever youngster, he thinks about how many ways...

3 minutes read.

Permutation Coefficient in Java

In this tutorial, we will get familiar with the permutation coefficient in Java.  We will understand it through examples and see different approaches to solving the problem. A permutation is a...

5 minutes read.

Java Naming Conventions

JAVA NAMING CONVENTIONS Java naming convention is a standard pattern for writing your identifier name such as class, interfaces, methods, constants, variable, etc. These patterns are not standard rules that you must...

2 minutes read.

Java Substring

What is a substring in Java? Here by the name  " substring " itself, we can easily come to know it is a part of a string or a subset of...

4 minutes read.

Difference between this and super in Java

In this article, you will be very well equipped with the knowledge of this keyword and super keyword in java. You will be able to understand where to implement this...

3 minutes read.

Heap Implementation in Java

The root node or parent node of a Java heap is compared to its left and right offspring, and the children are then ordered in line with the comparison.Assuming that...

9 minutes read.

Java Integer signum() method

The signum() method of Java Integer class returns the signum function of the specified int value. Syntax public static int signum (int i)  Parameters The parameter ‘i’ represents the value whose signum is to...

1 minute read.

Type Annotations in Java

Only declarations were eligible for annotations in earlier versions of Java. With Java 8, you may now annotate any type use, including types in declarations, generics, and casts: @Encrypted String data; List<@NonNull...

6 minutes read.

Java Destructors

Before knowing about Java destructors, let us know about constructors. If we understand the concept of the constructor, we can easily understand about destructor and also, we will get an...

3 minutes read.

Functional Interface in Java 8

A brief introduction to Interface in Java: Interfaces in Java are basically the blue print of classes. Before the appearance of Java 8, it was only possible to declare one or...

11 minutes read.

Graphics Program in Java

Graphics Program in Java The graphics program in Java is part of the Swing program in Java. In this section, we will learn about the implementation of custom graphics using some...

6 minutes read.

How to create a mirror image of a 2D array in Java

Problem Statement We have provided a list of m x n. here m indicates rows, and n indicates columns). Printing the fresh matrices should result in a mirror reflection of an...

2 minutes read.

Traverse through HashMap in Java

In this tutorial, we will discuss traversing through HashMap in Java Introduction: HashMap<Key, Value> is a part of the java collection implemented from the java 1.2 version. HashMap is written as HashMap<K,...

4 minutes read.

Union in Java

Sets.union() method in Java returns an immutable representation of both the union of two sets. Every element that is present in either backup set is included in the set that...

2 minutes read.

Java Set Interface

We use set when we don't want to allow duplicate entries. All Set implementations do not allow duplicates. HashSet: This class stores its elements in hash tables. It uses the hashCode()...

3 minutes read.