HOWTO · Java
How to Handle FileNotFoundException in Java
Learn what FileNotFoundException means in Java, how to handle it with try-with-resources, and how to diagnose missing or inaccessible files.
On this page
FileNotFoundException is a checked java.io.IOException that Java throws when it cannot open the file named by a given path — most often because the file does not exist, the path points to a directory, or the operating system refuses access. This tutorial explains what the FileNotFoundException means, shows how to handle it safely with try-with-resources, and walks through the checks that diagnose missing-path and access problems.
What FileNotFoundException Means in Java
java.io.FileNotFoundException extends java.io.IOException, which extends java.lang.Exception. Because it is a checked exception, code that opens a file must either catch it or declare it with throws; the compiler enforces that decision.
The constructors of FileInputStream, FileOutputStream, and RandomAccessFile declare it, and so do APIs built on them, such as FileReader, FileWriter, and new Scanner(new File(path)). The JVM raises it when the operating system’s open call fails — the named file cannot be found or cannot be opened in the requested mode. That covers several distinct situations, so a FileNotFoundException does not always mean a typing mistake: a missing parent directory, a path that names a directory, or denied permission produce the same type.
Why Java Throws FileNotFoundException
The common triggers are:
- The file does not exist at the path the program asked for, or a parent directory in the path is missing.
- The path exists but names a directory, which cannot be opened as a regular file.
- The file exists but the operating system denies the process access to it.
- For output streams, the target cannot be created, for example inside a read-only or missing directory.
Relative paths such as demo.txt are resolved against the process working directory — the user.dir system property, usually the directory where java was launched — not against the folder containing the .java or .class file. A program that works in one IDE and fails in a terminal is often just running from a different working directory.
Run this example to see a guaranteed failure and a focused catch:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class MissingFile {
public static void main(String[] args) {
String path = "missing-dir/demo.txt";
try (Scanner scanner = new Scanner(new File(path))) {
System.out.println(scanner.nextLine());
} catch (FileNotFoundException e) {
System.out.println("Cannot open " + path);
System.out.println("Cause: " + e.getClass().getName());
}
}
}
Cannot open missing-dir/demo.txt
Cause: java.io.FileNotFoundException
The catch reports the problem instead of crashing, so the program exits normally. Printing e.getMessage() would also show the operating system’s reason, but that text differs between platforms, so the class name is the portable detail to confirm.
Handle FileNotFoundException with try-with-resources
The safest way to read a file is to open the resource inside a try block and let Java close it automatically. The pattern is called try-with-resources: each variable declared in the parentheses must implement AutoCloseable, and Java closes every resource in reverse order — even when the body returns early or a failure occurs midway. Compared with manual finally cleanup, no reference can stay null, and no close call can be skipped or forgotten. The following program writes a short file into the system temp directory, reads its first line back through a Scanner, and prints that line to standard output.
Run this example:
import java.io.File;
import java.io.FileWriter;
import java.util.Scanner;
public class ReadFirstLine {
public static void main(String[] args) throws Throwable {
File temp = File.createTempFile("delftstack", ".txt");
temp.deleteOnExit();
try (FileWriter writer = new FileWriter(temp)) {
writer.write("Hello from DelftStack!");
}
try (Scanner scanner = new Scanner(temp)) {
System.out.println(scanner.nextLine());
}
}
}
Hello from DelftStack!
Any resource that implements AutoCloseable — Scanner, FileReader, BufferedReader, FileInputStream, and the NIO channel types — can sit in the parentheses. When the open itself can fail, keep the same shape and add a focused catch (FileNotFoundException e) after the block, as the previous section showed. Catching the FileNotFoundException tells you the open failed; it does not mean the read succeeded, so only report success when the body actually ran.
Diagnose a Missing File or Access Problem
When a FileNotFoundException appears, work through the path before touching the code:
- Print the resolved location.
new File(path).getAbsolutePath()andpath.toAbsolutePath()show where the program is actually looking, andSystem.getProperty("user.dir")shows the working directory a relative path is anchored to. - Check the spelling and case of every path segment. On Linux, file names are case-sensitive, so
Demo.txtis a different file fromdemo.txt; the default macOS and Windows filesystems are not case-sensitive, but the name must still match exactly as stored. Editors can also savedemo.txt.txtwhen the real extension is hidden. - Check whether the path names a directory. Opening a directory for reading or writing fails the same way.
- Check access.
Files.isReadableandFiles.isWritablereport what the process may do, and on Windows a file locked by another program can also fail to open. - For output files, confirm the parent directory exists and is writable.
The java.nio.file.Files probes below make the first checks explicit without opening the file:
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class CheckPath {
public static void main(String[] args) {
Path path = Paths.get("missing-dir", "demo.txt");
System.out.println("exists=" + Files.exists(path));
System.out.println("isDirectory=" + Files.isDirectory(path));
System.out.println("isRegularFile=" + Files.isRegularFile(path));
System.out.println("isReadable=" + Files.isReadable(path));
}
}
exists=false
isDirectory=false
isRegularFile=false
isReadable=false
When every probe returns false, the path points at nothing the process can see — a spelling, working-directory, or missing-file problem rather than a code bug.
Choose the Right Exception Handling
Catch FileNotFoundException specifically when a missing file has its own remedy: fall back to a default configuration, create the file, or prompt the user for another path. Catch the broader IOException when a failed open and a failed read or write all receive the same treatment — for example one log-and-abort path for the whole operation. If you write both handlers, the FileNotFoundException catch must come first, because it is the subclass.
Declare throws when the caller owns the decision — a library that only opens what it is told to open should let the failure travel up. Whatever the choice, do not swallow the exception or treat a caught failure as success: log it, return a clear result, or rethrow it as an unchecked type such as IllegalStateException when the missing file signals a programming or deployment bug.