FileNotFoundException in Java – Causes, Examples, and Complete Fix Guide

FileNotFoundException is one of the most common checked exceptions in Java, especially when working with file handling and input/output (I/O) operations. It occurs when a Java program attempts to open or read a file that does not exist, cannot be located, or cannot be accessed due to permission issues.

Whether you’re reading a text file, loading a configuration file, processing CSV data, or uploading documents, understanding FileNotFoundException is essential for writing reliable Java applications.

In this comprehensive guide, you’ll learn what FileNotFoundException is, why it occurs, common causes, practical examples, and the best ways to fix and prevent it.

What is FileNotFoundException?

FileNotFoundException is a checked exception that belongs to the java.io package.

It is thrown when an application attempts to:

  • Open a file that does not exist.
  • Access a file using an incorrect path.
  • Open a directory as if it were a file.
  • Access a file without sufficient permissions.

Example error:

Exception in thread “main”

java.io.FileNotFoundException:

data.txt (The system cannot find the file specified)

Because it is a checked exception, Java requires you to either handle it using a try-catch block or declare it with the throws keyword.

Why Does FileNotFoundException Occur?

Java throws FileNotFoundException whenever it cannot successfully open a file for reading or writing.

Common situations include:

  • The file does not exist.
  • The filename is misspelled.
  • The file path is incorrect.
  • The application lacks permission to access the file.
  • The file has been deleted.
  • The file is locked by another process.
  • A directory is used instead of a file.

Common Causes of FileNotFoundException

Some of the most common causes include:

  • Incorrect file path
  • Wrong filename
  • Missing file extension
  • Relative path issues
  • File deleted after deployment
  • Insufficient file permissions
  • Reading from a non-existent directory
  • Typographical errors
  • Using the wrong working directory
  • Attempting to open a folder as a file

Example 1: Reading a Non-Existent File


import java.io.FileInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;

public class Main {

    public static void main(String[] args)
            throws FileNotFoundException {

        FileInputStream file =
                new FileInputStream("students.txt");
    }
}

Output:

Exception in thread “main”
java.io.FileNotFoundException:
students.txt

Since the file does not exist, Java throws the exception.

Example 2: Incorrect File Path


FileInputStream file =
new FileInputStream("C:/Data/users.txt");

If the file is actually stored in:


C:/Documents/users.txt

Java cannot locate it and throws FileNotFoundException.

How FileNotFoundException Works

Whenever classes such as:

  • FileInputStream
  • FileReader
  • Scanner
  • RandomAccessFile

attempt to open a file, Java first verifies:

  • Does the file exist?
  • Is the path correct?
  • Is the file accessible?
  • Does the application have permission?

If any of these checks fail, FileNotFoundException is thrown.

Solution 1: Verify the File Exists

Before opening a file, check whether it exists.


import java.io.File;

File file = new File("students.txt");

if (file.exists()) {

    System.out.println("File found.");

} else {

    System.out.println("File does not exist.");
}

Using exists() helps avoid unnecessary exceptions.

Solution 2: Use the Correct File Path

Incorrect:


FileReader reader =
new FileReader("student.txt");

Correct:


FileReader reader =
new FileReader("C:/Users/Admin/Documents/student.txt");

Always ensure the file path is accurate.

Solution 3: Handle the Exception

Use a try-catch block to prevent the application from crashing.


import java.io.FileReader;
import java.io.FileNotFoundException;

public class Main {

    public static void main(String[] args) {

        try {

            FileReader reader =
                    new FileReader("students.txt");

        } catch (FileNotFoundException e) {

            System.out.println("File not found.");
        }
    }
}

Output:

File not exist.

Solution 4: Use Relative Paths Carefully

Suppose your project structure is:


Project
│
├── data
│   └── users.txt
│
└── src

Use:


new FileReader("data/users.txt");

Remember that relative paths are resolved from the application’s current working directory, which may differ between an IDE and a deployed application.

Solution 5: Check File Permissions

Sometimes the file exists but cannot be accessed.

Example:


File file = new File("data.txt");
System.out.println(file.canRead());

If it prints:

false

the application does not have read permission.

Ensure the file has the required read/write permissions.

Solution 6: Avoid Typographical Errors

Incorrect:


new FileReader("Employe.txt");

Actual filename:


Employee.txt

Even a small spelling mistake or incorrect capitalization on case-sensitive operating systems can result in FileNotFoundException.

Solution 7: Create the File If Necessary

Before reading:


File file = new File("report.txt");

if (!file.exists()) {

    file.createNewFile();
}

This approach is useful for log files and configuration files that should exist before being read.

Solution 8: Verify the Working Directory

Sometimes developers assume the application is running from a different folder.

Print the current working directory:


System.out.println(
System.getProperty("user.dir"));

This helps identify why a relative path is failing.

Solution 9: Use try-with-resources

Instead of manually closing files:


try (FileReader reader =
        new FileReader("students.txt")) {

    // Read file

} catch (FileNotFoundException e) {

    System.out.println("File not found.");
}

This automatically closes the file resource and makes the code cleaner.

Solution 10: Use Absolute Paths for Testing

During development:


new FileReader(
"C:/Users/Admin/Desktop/data.txt");\

For production applications, prefer configurable paths or resource files instead of hardcoded absolute paths.

Solution 11: Package Resources Correctly

If reading files packaged with your application (such as configuration files or templates), use the class loader:


InputStream input =
Main.class.getResourceAsStream("/config.properties");

This is more reliable than using filesystem paths for resources bundled inside JAR files.

Solution 12: Validate User-Provided File Names

Suppose users upload a filename.

Incorrect:


new FileReader(userInput);

Correct:


File file = new File(userInput);

if (file.exists()) {

    FileReader reader =
            new FileReader(file);

} else {

    System.out.println("Invalid file.");
}

Always validate user input before attempting file access.

Real-World Example

Incorrect implementation:


import java.io.FileReader;

public class Main {

    public static void main(String[] args)
            throws Exception {

        FileReader reader =
                new FileReader("marks.txt");
    }
}

Output:

Exception in thread “main”
java.io.FileNotFoundException:
marks.txt

Correct implementation:


import java.io.File;
import java.io.FileReader;

public class Main {

    public static void main(String[] args) {

        try {

            File file = new File("marks.txt");

            if (file.exists()) {

                FileReader reader =
                        new FileReader(file);

                System.out.println("File opened successfully.");

            } else {

                System.out.println("File does not exist.");
            }

        } catch (Exception e) {

            System.out.println(e.getMessage());
        }
    }
}

Output (if the file is missing):

File does not exist.

Common Scenarios That Cause FileNotFoundException

Scenario Solution
File does not exist Verify the file exists before opening
Incorrect file path Use the correct absolute or relative path
Misspelled filename Double-check spelling and extension
Wrong working director Print user.dir to verify location
Missing file extension Use the correct filename (e.g., .txt, .csv)
No read permission Grant the required file permissions
Opening a directory as a file Ensure the path points to a file
Deleted file Restore or recreate the file
User-provided filename Validate before opening
Packaged resources Use getResourceAsStream()

Best Practices to Prevent FileNotFoundException

Follow these recommendations:

  • Always verify that a file exists before opening it.
  • Use try-catch to handle FileNotFoundException.
  • Avoid hardcoded file paths in production code.
  • Validate user-provided file names and paths.
  • Use configurable file locations.
  • Check file permissions before reading or writing.
  • Print the working directory when debugging path issues.
  • Use try-with-resources for automatic resource management.
  • Package application resources correctly.
  • Test your application on different operating systems to avoid path-related issue.

Frequently Asked Questions (FAQs)

What is FileNotFoundException in Java?

FileNotFoundException is a checked exception thrown when Java cannot locate or access a file during file input or output operations.

Is FileNotFoundException a checked exception?

Yes. It extends IOException, making it a checked exception. Java requires you to either handle it with a try-catch block or declare it using the throws keyword.

Which classes can throw FileNotFoundException?

Common classes include:

  • FileInputStream
  • FileOutputStream
  • FileReader
  • FileWriter (in some situations)
  • Scanner
  • RandomAccessFile

How do I fix FileNotFoundException?

You can fix it by:

  • Verifying that the file exists.
  • Using the correct file path.
  • Checking file permissions.
  • Handling the exception using try-catch.
  • Validating user input.
  • Confirming the application’s working directory.
  • Using classpath resources for bundled files.

Conclusion

FileNotFoundException is one of the most common exceptions encountered while working with Java file handling. It usually occurs because a file is missing, the path is incorrect, the application lacks permission to access the file, or the wrong working directory is being used. Fortunately, it is easy to prevent by validating file existence, using accurate paths, handling exceptions properly, checking permissions, and following best practices for resource management. By understanding the causes of FileNotFoundException and applying the solutions discussed in this guide, you can build Java applications that handle file operations safely, efficiently, and reliably.

Related Java Tutorials