java.io.FileNotFoundException
java.io.FileNotFoundException
DodaTech
3 min read
FileNotFoundException is thrown when Java cannot open a file — the path is wrong, the file doesn’t exist, or the process lacks OS permissions to read or write it.
What It Means
A FileInputStream, FileReader, RandomAccessFile, or similar I/O class tried to access a file at the specified path, but the OS returned an error. Java wraps this into FileNotFoundException. The message usually includes the path that was attempted.
Why It Happens
- The file path is incorrect (typo, wrong directory).
- The file doesn’t exist at the specified location.
- The application’s working directory is not what you expect.
- The file exists but the process doesn’t have read permission.
- On Windows, another process has the file locked exclusively.
- You’re using a relative path when an absolute path is needed.
How to Fix It
1. Print the working directory
// Discover where your app is running from
System.out.println("Working dir: " + System.getProperty("user.dir"));
// Now use a path relative to that directory
File file = new File("data/config.properties");2. Use absolute paths or build from known locations
// BUG: relative path may not resolve as expected
FileInputStream fis = new FileInputStream("config.properties");
// FIX: use absolute path
FileInputStream fis = new FileInputStream("/opt/myapp/config.properties");
// Or build from a known base
String home = System.getProperty("user.home");
File config = new File(home, ".myapp/config.properties");3. Check file existence and handle gracefully
File file = new File("data/input.txt");
if (!file.exists()) {
System.err.println("File not found: " + file.getAbsolutePath());
return;
}
if (!file.canRead()) {
System.err.println("Cannot read file: " + file.getAbsolutePath());
return;
}
// Safe to read
try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
reader.lines().forEach(System.out::println);
}4. Use getResourceAsStream for bundled files
// For files bundled in the JAR or classpath
// Good for config files bundled with your app
try (InputStream in = getClass()
.getResourceAsStream("/config/default.properties")) {
if (in == null) {
throw new FileNotFoundException(
"Resource not found: /config/default.properties"
);
}
Properties props = new Properties();
props.load(in);
}5. Create parent directories before writing
File output = new File("/var/log/myapp/output.log");
// Ensure parent directory exists
File parent = output.getParentFile();
if (parent != null && !parent.exists()) {
parent.mkdirs(); // creates all missing parent directories
}
try (FileWriter writer = new FileWriter(output)) {
writer.write("Log entry");
} Previous
HTTP 409 Conflict — What It Means & How to Debug
Next
ValueError: invalid literal for int() with base 10
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro