Sotirios-Efstathios Maneas

About Sotirios-Efstathios Maneas

Sotirios-Efstathios (Stathis) Maneas is a postgraduate student at the Department of Informatics and Telecommunications of The National and Kapodistrian University of Athens. His main interests include distributed systems, web crawling, model checking, operating systems, programming languages and web applications.

java.io.FileNotFoundException – How to solve File Not Found Exception

In this tutorial we will discuss about the 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.

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).

 

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 FileNotFoundException is thrown.

FileNotFoundExceptionExample.java:

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;

public class FileNotFoundExceptionExample {
	
	private static final String filename = "input.txt";
	
	public static void main(String[] args) {
		BufferedReader rd = null;
		try {
			// Open the file for reading.
			rd = new BufferedReader(new FileReader(new File(filename)));
			
			// Read all contents of the file.
			String inputLine = null;
			while((inputLine = rd.readLine()) != null)
				System.out.println(inputLine);
		}
		catch(IOException ex) {
			System.err.println("An IOException was caught!");
			ex.printStackTrace();
		}
		finally {
			// Close the file.
			try {
				rd.close();
			}
			catch (IOException ex) {
				System.err.println("An IOException was caught!");
				ex.printStackTrace();
			}
		}
	}
}

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:

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

public class FileNotFoundExceptionExample_v2 {
	
	private static final String filename = "input.txt";
	
	public static void main(String[] args) {
		BufferedWriter wr = null;
		try {
			// Open the file for writing, without removing its current content.
			wr = new BufferedWriter(new FileWriter(new File(filename), true));
			
			// Write a sample string to the end of the file.
			wr.write("A sample string to be written at the end of the file!\n");
		}
		catch(IOException ex) {
			System.err.println("An IOException was caught!");
			ex.printStackTrace();
		}
		finally {
			// Close the file.
			try {
				wr.close();
			}
			catch (IOException ex) {
				System.err.println("An IOException was caught!");
				ex.printStackTrace();
			}
		}
	}
}

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.

How to deal with the 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.

Download the Eclipse Project

The Eclipse project of this example: FileNotFoundExceptionExample.zip

 
This was a tutorial about the FileNotFoundException in Java.

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

JPA Mini Book

Learn how to leverage the power of JPA in order to create robust and flexible Java applications. With this Mini Book, you will get introduced to JPA and smoothly transition to more advanced concepts.

JVM Troubleshooting Guide

The Java virtual machine is really the foundation of any Java EE platform. Learn how to master it with this advanced guide!

Given email address is already subscribed, thank you!
Oops. Something went wrong. Please try again later.
Please provide a valid email address.
Thank you, your sign-up request was successful! Please check your e-mail inbox.
Please complete the CAPTCHA.
Please fill in the required fields.
Examples Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy | Contact
All trademarks and registered trademarks appearing on Examples Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Examples Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.
Do you want to know how to develop your skillset and become a ...
Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

Get ready to Rock!
You can download the complementary eBooks using the links below:
Close