FileNotFoundException Java Example

This Java example demonstrates the usage of 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 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;



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!");
FileNotFoundException caught! \invalid\file\location (The system cannot find the path specified)
 at Method)
 at com.javaguides.corejava.FileNotFoundExceptionExample.main(

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