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!
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")
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
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:
- 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.
java.io.FileNotFoundException, которое является распространенным исключением, которое возникает, когда мы пытаемся получить доступ к файлу. FileNotFoundExcetion создается конструкторами RandomAccessFile, FileInputStream и FileOutputStream. FileNotFoundException возникает во время выполнения, поэтому это проверенное исключение, мы можем обработать это исключение с помощью java-кода, и мы должны позаботиться о коде, чтобы это исключение не произошло.
Декларация:
открытый класс FileNotFoundException
расширяет IOException
реализует ObjectInput, ObjectStreamConstants
Конструкторы:
- FileNotFoundException (): выдает исключение FileNotFoundException с нулевым сообщением.
- FileNotFoundException (String s): выдает исключение FileNotFoundException с подробным сообщением.
У него нет никаких методов. Теперь давайте разберемся в иерархии этого класса, т.е. FileNotFoundException расширяет IOException, который дополнительно расширяет класс Exception, который расширяет класс Throwable и далее класс Object.
Схема иерархии:

Почему возникает это исключение?
Есть в основном 2 сценария, когда возникает исключение FileNotFoundException. Теперь давайте посмотрим на них с предоставленными примерами:
- Если данный файл недоступен в указанном месте, возникнет эта ошибка.
- Если данный файл недоступен , например, если он доступен только для чтения, вы можете прочитать файл, но не изменить файл, если мы попытаемся изменить его, произойдет ошибка или если файл, к которому вы пытаетесь получить доступ, операция чтения / записи открывается другой программой, тогда возникает эта ошибка.
Сценарий 1:
Если данный файл недоступен в указанном месте, возникнет эта ошибка.
Пример:
Ява
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 ;
в ((data = br.readLine()) != null ) while ((data = br.readLine()) != null )
{
System.out.println(data);
}
br.close();
}
}
Выход
prog.java:14: ошибка: незарегистрированное исключение FileNotFoundException; должен быть пойман или объявлен брошенным
FileReader reader = новый FileReader ("file.txt");
^
prog.java:25: ошибка: незарегистрированное исключение IOException; должен быть пойман или объявлен брошенным
в то время как ((данные = br.readLine ())! = ноль)
^
prog.java:31: ошибка: незарегистрированное исключение IOException; должен быть пойман или объявлен брошенным
br.close ();
^
3 ошибки
Сценарий 2:
Если данный файл недоступен, например, если он доступен только для чтения, вы можете прочитать файл, но не изменить файл, если мы попытаемся его изменить, произойдет ошибка или если файл, к которому вы пытаетесь получить доступ, для операция чтения / записи открывается другой программой, тогда возникает эта ошибка.
Пример:
Ява
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();
}
}
}
Выход
java.security.AccessControlException: доступ запрещен ("java.io.FilePermission" "file.txt" "запись")
в java.base / java.security.AccessControlContext.checkPermission (AccessControlContext.java:472)
в java.base / java.security.AccessController.checkPermission (AccessController.java:897)
в java.base / java.lang.SecurityManager.checkPermission (SecurityManager.java:322)
в java.base / java.lang.SecurityManager.checkWrite (SecurityManager.java:752)
в java.base / java.io.FileOutputStream. <init> (FileOutputStream.java:225)
в java.base / java.io.FileOutputStream. <init> (FileOutputStream.java:187)
в java.base / java.io.FileWriter. <init> (FileWriter.java:96)
в Example2.main (File.java:19)
Обработка исключения:
Во-первых, мы должны использовать блок try-catch, если мы знаем, произойдет ли ошибка. Внутри блока try все строки должны быть там, если есть вероятность ошибок. Есть и другие средства для обработки исключения:
- Если сообщение об исключении сообщает, что такого файла или каталога нет, то вы повторно проверяете, упомянули ли вы неправильное имя файла в программе или файл существует в этом каталоге или нет.
- Если сообщение об исключении сообщает нам, что доступ запрещен, мы должны проверить права доступа к файлу (чтение, запись, чтение и запись), а также проверить, используется ли этот файл другой программой.
- Если сообщение об исключении сообщает нам, что указанный файл является каталогом, вы должны либо удалить существующий каталог (если каталог не используется), либо изменить имя файла.
Вниманию читателя! Не прекращайте учиться сейчас. Ознакомьтесь со всеми важными концепциями Java Foundation и коллекций с помощью курса «Основы Java и Java Collections» по доступной для студентов цене и будьте готовы к работе в отрасли. Чтобы завершить подготовку от изучения языка к DS Algo и многому другому, см. Полный курс подготовки к собеседованию .
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:

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).
1. The FileNotFoundException in Java

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 |
|
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 |
|
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
FileNotFoundException is a checked exception therefore we must catch or handle it. It is a subclass of IOException and is defined in the java.io package. Generally, FileNotFoundException will be thrown by the FileInputStream, FileReader, and RandomAccessFile constructors, where file information is the source and must be passed to the constructor. Here we will discuss the different reasons for getting this exception.
Unhandled exception type FileNotFoundException
FileNotFoundException is a checked exception, and at compile time compiler checks whether we are handling FileNotFoundException or not.
It means if there is a chance to raise FileNotFoundException in the statement then we must handle the FileNotFoundException either by using try-catch block or by using the throws keyword.
Unreported Exception FileNotFoundException; must be caught or declared to be thrown
If we don’t handle FileNotFoundException then the compiler gives the compile-time error: unreported exception FileNotFoundException; must be caught or declared to be thrown.
Example:- FileReader class is used to read character data from the file. The constructor of FileReader class throws FileNotFoundException.
import java.io.FileReader;
public class Test {
public static void main(String[] args) {
FileReader fr = new FileReader("data.txt");
// .......
}
}
Since we don’t handle FileNotFoundException therefore we will get the compile-time error:- unreported exception FileNotFoundException; must be caught or declared to be thrown,
While compilation,
FileReaderDemo.java:6: error: unreported exception
FileNotFoundException; must be caught or declared to be thrown
FileReader fr = new FileReader(“data.txt”);
^
1 error
Solution of compile-time error: unreported exception FileNotFoundException; must be caught or declared to be thrown,
- Catch this exception using try/catch block
- Handle this exception using throws
But before catching and handling the exception we must import FileNotFoundException or java.io package. While catching or handling the exception we can also use superclass exception, Exception, or Throwable. The Throwable is the superclass for all Exceptions.
// Java program to handle the exception
import java.io.FileReader;
import java.io.FileNotFoundException;
public class Test {
public static void main(String[] args)
throws FileNotFoundException {
FileReader fr = new FileReader("data.txt");
// .......
}
}
Using throws we are informing the caller method that the called method may throw FileNotFoundException. Now, it’s the responsibility of the caller method to catch or handle the exception.
import java.io.FileReader;
import java.io.FileNotFoundException;
public class Test {
public static void main(String[] args) {
try {
FileReader fr = new FileReader("data.txt");
// .......
} catch (FileNotFoundException fnfe) {
fnfe.printStackTrace();
}
}
}
Using try/catch block we are catching the exception. We can finally block to close the stream also.
Different Reasons to Get FileNotFoundException in Java
We will get runtime exception in the following cases,
- The passed named File is not available.
- Available but it is a directory rather than a normal file.
- The file doesn’t have reading/writing permission.
- Access permission is not there.
If the given name is a directory/folder, not a file then also we will get the same exception with “Access is denied”.
In all Writer and Output classes, we won’t get FileNotFoundException because the file is not available. These classes are made for writing the data and need destination file information, if the file is not available then their constructors can create an empty file with the given name itself, and then write the data into the file. They are FileNotFoundException for another reason like file creation permission is not there, it is available but represents directory/folder, or file is available but writing permission is not there.
Most of the time, Windows C drive doesn’t allow to create a file, it only gives permission to create a directory. In this case, we can get FileNotFoundException. We can get an exception:- Exception in thread “main” java.io.FileNotFoundException: C:xyz.txt (Access is denied). Similarly, in Linux/Unix OS, we can’t create files in other user directories.
In all Reader and Input classes file is the source from where the Java application will collect the data. And in this case, the file must be available else we will get FileNotFoundException. Other reasons are:- it is a folder rather than a file, access permission is not there.
If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or do you find anything incorrect? Let us know in the comments. Thank you!