Home โบ Java exceptions โบ FileNotFoundException
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
- A relative path resolved against an unexpected working directory.
- The file is inside the jar: files under
src/main/resourcesare classpath resources, not files on disk. - File permissions or a read-only container file system.
- Windows versus Linux differences: case sensitivity, back slashes, drive letters.
How to fix it
- Print
new File(path).getAbsolutePath()to see what is really being opened. - Load packaged files with
getResourceAsStream("/name")or Spring'sClassPathResource, notFileInputStream. - Use
java.nio.file.PathandFiles.existsand give the path through configuration. - In containers, mount the file or directory and check the user's permissions.
Broken and fixed
new FileInputStream("src/main/resources/data.csv"); // fails in the packaged jartry (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.