FileNotFoundException
JavaERRORCommonI/O
File does not exist or cannot be opened
Quick Answer
Use Files.exists() before opening and prefer absolute paths to avoid working-directory surprises.
What this means
Thrown when an attempt to open a file fails because the file does not exist or the path is inaccessible.
Why it happens
- 1Relative path resolves to wrong directory at runtime
- 2File was deleted between existence check and open
Fix
NIO2 with explicit existence check
NIO2 with explicit existence check
Path p = Paths.get("/etc/config.json");
if (Files.exists(p)) {
try (var r = Files.newBufferedReader(p)) { /* read */ }
}Why this works
Absolute paths eliminate working-directory confusion.
Code examples
Triggerjava
new FileInputStream("missing.txt"); // FileNotFoundExceptionNIO2 safe openjava
try (var in = Files.newInputStream(path)) {
// read safely
} catch (NoSuchFileException e) {
System.err.println("Not found: " + path);
}Create parent dirs firstjava
Files.createDirectories(path.getParent()); Files.writeString(path, content);
Same error in other languages
Sources
Official documentation ↗
Java SE Documentation
Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev