FileNotFoundException in Java

If you are working with the File APIs in Java, it is common that you would encounter the FileNotFoundException. This exception is thrown by the classes FileInputStream, FileOutputStream, and RandomAccessFile. These classes trying to access a file in the system for the purposes of reading or writing into that file. Java doesn’t have the facility to check if the file is present at the compile time. When you execute the program, you would get the FileNotFoundException if that file is not exist.

It is a checked exception that must be handled by the application. Take the appropriate steps to print the valid messages to the user if this exception is thrown. Look at the below example:

package javabeat.net.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
/**
 * File Not Found Exception example
 * @author Krishna
 *
 */
public class JavaFileExample {
	public static void main(String[] args) {
		File file = new File("D:/JavaTest.txt");
		FileInputStream fileInputStream = null;
		try{
			fileInputStream = new FileInputStream(file);
			while (fileInputStream.read()!=-1){
				System.out.println(fileInputStream.read());
			}
		}catch (FileNotFoundException e){
			e.printStackTrace();
		}catch (IOException e){
			e.printStackTrace();
		}finally{
			try{
				fileInputStream.close();
			}catch (IOException e){
				e.printStackTrace();
			}
		}
	}
}

The above program would throw an exception if the file “JavaText.txt” is not in the mentioned path. You will get the following exception.

java.io.FileNotFoundException: D:\JavaTest.txt (The system cannot find the file specified)
	at java.io.FileInputStream.open(Native Method)
	at java.io.FileInputStream.<init>(Unknown Source)
	at javabeat.net.util.JavaFileExample.main(JavaFileExample.java:17)
Exception in thread "main" java.lang.NullPointerException
	at javabeat.net.util.JavaFileExample.main(JavaFileExample.java:27)

Comments

comments

About Krishna Srinivasan

He is Founder and Chief Editor of JavaBeat. He has more than 8+ years of experience on developing Web applications. He writes about Spring, DOJO, JSF, Hibernate and many other emerging technologies in this blog.

Speak Your Mind

*