-
Notifications
You must be signed in to change notification settings - Fork 4
Java FileNotFoundException Example
Ramesh Fadatare edited this page Jul 12, 2019
·
1 revision
This Java example demonstrates the usage of java.io.FileNotFoundException class with an example.
-
FileNotFoundException signals that an attempt to open the file denoted by a specified pathname has failed.
-
This exception will be thrown by the FileInputStream, FileOutputStream, and RandomAccessFile constructors when a file with the specified pathname does not exist. It will also be thrown by these constructors if the file does exist but for some reason is inaccessible, for example when an attempt is made to open a read-only file for writing.
In this below example, invalid path location passed to File constructor leads to this exception.
package com.javaguides.corejava;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
public class FileNotFoundExceptionExample {
public static void main(String[] args) {
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(new File("/invalid/file/location")));
} catch (FileNotFoundException e) {
System.err.println("FileNotFoundException caught!");
e.printStackTrace();
}
}
}
Output:
FileNotFoundException caught!
java.io.FileNotFoundException: \invalid\file\location (The system cannot find the path specified)
at java.io.FileInputStream.open0(Native Method)
at java.io.FileInputStream.open(FileInputStream.java:195)
at java.io.FileInputStream.<init>(FileInputStream.java:138)
at java.io.FileReader.<init>(FileReader.java:72)
at com.javaguides.corejava.FileNotFoundExceptionExample.main(FileNotFoundExceptionExample.java:15)