java.io.FileNotFoundException
ID: java/filenotfoundexception
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| 17 | active | — | — | — |
Root Cause
FileNotFoundException is thrown when an attempt to open a file denoted by a path fails because the file does not exist, the path is a directory, or the file cannot be opened for the requested access (permission denied on some systems).
genericWorkarounds
-
92% success Use classpath resources (getResourceAsStream) for files bundled with the application
1. Place the file in src/main/resources/. 2. Load it using: getClass().getResourceAsStream('/config.json') or Thread.currentThread().getContextClassLoader().getResourceAsStream('config.json'). 3. This works regardless of the working directory because the file is read from the classpath (inside the JAR). 4. Always check for null return (resource not found). 5. For Spring: use @Value('classpath:config.json') Resource configFile. -
90% success Use configurable paths via environment variables or system properties for external files
1. Define the path as a configurable property: String path = System.getenv('CONFIG_PATH'); or use Spring's @Value('${config.path}'). 2. Validate the path at startup with Files.exists(Path.of(path)). 3. Use Path.of() instead of new File() for proper path handling. 4. Log the resolved absolute path to aid debugging: logger.info('Loading config from: {}', path.toAbsolutePath()). 5. Provide a sensible default that works in the development environment.
Dead Ends
Common approaches that don't work:
-
Hardcoding absolute file paths that work on the developer's machine
80% fail
Absolute paths like '/home/developer/project/config.json' or 'C:\Users\dev\config.json' are not portable. They break on CI/CD servers, Docker containers, other developers' machines, and production deployments where the directory structure differs.
-
Using relative paths without understanding the working directory at runtime
65% fail
Relative paths are resolved against the current working directory, which varies depending on how the application is launched (IDE, Maven, JAR, Docker). The file may exist in the project but the working directory at runtime is different from what the developer expects.