FileNotFoundException Java Example

This Java example demonstrates the usage of java.io.FileNotFoundException class and when this exception occurs 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.

FileNotFoundException Class Diagram

From the above class diagram, it extends java.io.IOException that extends java.lang.Exception.

Java FileNotFoundException Example

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)

Tips to handle this exception

  • Check if the passed file is present in a specified location
  • Check if the passed file is actually a directory
  • The passed file can not be open due to permission issues. You might be trying to write to file whereas you only have read permission.
  • Check if the passed file name does not contain any invisible characters such as \r\n symbols.

Free Spring Boot Tutorial | Full In-depth Course | Learn Spring Boot in 10 Hours


Watch this course on YouTube at Spring Boot Tutorial | Fee 10 Hours Full Course