BackendBench
Coffee

Home โ€บ Java exceptions โ€บ FileNotFoundException

Checked exception ยท java.io

FileNotFoundException: causes and fixes

A file could not be opened: it does not exist, is a directory, or the process lacks permission.

What it looks like

java.io.FileNotFoundException: config/app.json (No such file or directory)

Extends IOException in java.io.

What it means

The text in parentheses is the operating system's reason, and it matters more than the exception name: No such file or directory, Permission denied, Is a directory or The system cannot find the path specified. Relative paths are resolved against the process working directory, which is not the project folder when the app runs from an IDE, a service or a container, and that is the single most common cause.

Common causes

How to fix it

  1. Print new File(path).getAbsolutePath() to see what is really being opened.
  2. Load packaged files with getResourceAsStream("/name") or Spring's ClassPathResource, not FileInputStream.
  3. Use java.nio.file.Path and Files.exists and give the path through configuration.
  4. In containers, mount the file or directory and check the user's permissions.

Broken and fixed

fails
new FileInputStream("src/main/resources/data.csv"); // fails in the packaged jar
works
try (InputStream in = getClass().getResourceAsStream("/data.csv")) {
    // read from the classpath
}

๐Ÿ”Ž Unravel the failing code ๐Ÿ”Ž Unravel the fix

Debug it faster

Paste the whole stack trace into the stack trace beautifier to hide framework frames, jump to the root cause and find the first line of your own code. It runs in your browser, so the trace never leaves your machine.

Frequently asked questions

Is FileNotFoundException a checked or unchecked exception?

FileNotFoundException is a checked exception (it extends IOException), so the compiler forces you to catch it or declare it with throws.

Which package is FileNotFoundException in?

It lives in java.io, so the import is import java.io.FileNotFoundException;.

What is the first thing to check when I see FileNotFoundException?

Read the message and the first stack trace line in your own code. The usual causes are: A relative path resolved against an unexpected working directory; and The file is inside the jar: files under src/main/resources are classpath resources, not files on disk.

Related exceptions

More tools you might need