java.io.FileNotFoundException in Java
Last Updated :
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.
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 package
import 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();
}
}
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
// Java program to illustrate
// FileNotFoundException
// All output and input streams
// are available in java.io package
import 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();
}
}
}
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:
- 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.
Similar Reads
How to Handle an IOException in Java?
An IOException in Java occurs when we try to perform some input or output tasks and then some issues occur. Programmers need to handle this issue explicitly with a piece of code that executes when an issue occurs. There is an entire class for handling such issues known as the IOException class, whic
3 min read
Java Program to Handle Checked Exception
Checked exceptions are the subclass of the Exception class. These types of exceptions need to be handled during the compile time of the program. These exceptions can be handled by the try-catch block or by using throws keyword otherwise the program will give a compilation error. Â ClassNotFoundExcept
5 min read
How to Solve java.lang.IllegalStateException in Java main Thread?
An unexpected, unwanted event that disturbed the normal flow of a program is called Exception. Most of the time exception is caused by our program and these are recoverable. Example: If our program requirement is to read data from the remote file locating in U.S.A. At runtime, if a remote file is no
5 min read
Java File Handling Programs
Java is a programming language that can create applications that work with files. Files are containers that store data in different formats, such as text, images, videos, etc. Files can be created, read, updated, and deleted using Java. Java provides the File class from the java.io package to handle
3 min read
Implement how to load File as InputStream in Java
Problem Statement: There is a file already existing in which the same file needs to be loaded using the InputStream method. Concept: While accessing a file either the file is being read or write. here are two streams namely fileInputStream and fileOutputStream Java Stream is the flow of data from
4 min read
Java Program to Handle the Exception Hierarchies
Exceptions are the events that occur due to the programmer error or machine error which causes a disturbance in the normal flow of execution of the program and terminates the program. Exception Handling: The process of dealing with exceptions is known as Exception Handling. Hierarchy of Exceptions:
4 min read
How to Create a Directory in Java?
In Java, creating a directory is a common operation when working with file system manipulation. Directories are used to organize files and other directories into a hierarchical structure. This article will guide you through the process of creating a directory in Java, providing step-by-step examples
2 min read
How to List all Files in a Directory in Java?
Java provides a feature to interact with the file system through the java.io.file package. This feature helps developers automate the things to operate with files and directories. In this article, we will learn how to list all the files in a directory in Java. Approaches to list all files in a direc
3 min read
How to Lock a File in Java?
In Java, file locking involves stopping processes or threads from changing a file. It comes in handy for threaded applications that require simultaneous access, to a file or to safeguard a file from modifications while it's being used by our application. When reading or writing files we need to make
2 min read
How to Delete Temporary File in Java?
In java, we have a java.io package that provides various methods to perform various operations on files/directories. Temporary files are those files that are created for some business logic or unit testing, and after using these files you have to make sure that these temporary files should be delet
2 min read