Practical examples of file not found error examples in Java (and how to fix them)
Real examples of file not found error examples in Java
Let’s start with real code. All of these examples of file not found error examples in Java are based on situations that show up constantly in logs, Stack Overflow questions, and production incidents.
FileInputStream fis = new FileInputStream("config.properties");
Properties props = new Properties();
props.load(fis);
On a developer laptop, this often works. In production, the same code throws:
java.io.FileNotFoundException: config.properties (No such file or directory)
Why? Because config.properties is a relative path. The JVM tries to resolve it against the current working directory, which is different when you run from an IDE, from a JAR, or from a service manager.
This is the core theme across most examples of file not found error examples in Java: the file path you think you’re using is not the path the JVM is actually using.
Classic example of FileNotFoundException: wrong working directory
A very common example of a file not found error in Java looks harmless:
public class App {
public static void main(String[] args) throws IOException {
File file = new File("data/input.txt");
try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
System.out.println(reader.readLine());
}
}
}
Run it from your IDE with data/input.txt under the project root and it works. Package it as a JAR and run:
java -jar app.jar
Suddenly you get:
java.io.FileNotFoundException: data/input.txt (No such file or directory)
The problem isn’t the file; it’s where Java is looking. The working directory is now the directory where you ran the java command, not the project root.
How to fix it
Instead of assuming the working directory, either:
Use an absolute path from configuration:
String path = System.getProperty("input.file.path"); File file = new File(path);Or load the file as a classpath resource if it ships with the app:
InputStream is = App.class.getResourceAsStream("/data/input.txt");
This is one of the best examples of how environment differences trigger file not found errors in Java.
Examples of file not found error examples in Java with classpath resources
Another modern example of FileNotFoundException shows up when developers confuse the file system with the classpath. For instance:
File file = new File("/resources/schema.sql");
try (FileInputStream fis = new FileInputStream(file)) {
// use schema
}
This compiles but fails at runtime with:
java.io.FileNotFoundException: /resources/schema.sql (No such file or directory)
When you build a JAR, schema.sql typically lives inside the JAR on the classpath, not as a plain file at /resources/schema.sql.
Better pattern
Use the classloader instead of File:
try (InputStream is = App.class.getResourceAsStream("/schema.sql")) {
if (is == null) {
throw new IllegalStateException("schema.sql not found on classpath");
}
// read from InputStream
}
This is one of the most common examples of file not found error examples in Java when migrating from local development to containerized or JAR-based deployments.
For background on how the classpath works and why JARs behave like this, Oracle’s Java tutorials are still a solid reference: https://docs.oracle.com/javase/tutorial/.
OS‑specific path mistakes: Windows vs Linux examples
Another family of examples of file not found error examples in Java comes from hard‑coding paths that only make sense on one operating system.
Hard‑coded Windows drive letters
You might see something like:
File logFile = new File("C:/logs/app.log");
This runs fine on a Windows developer laptop. Deploy the same code to a Linux server and you’ll hit:
java.io.FileNotFoundException: C:\logs\app.log (No such file or directory)
Linux has no C: drive, so the path is meaningless.
Safer approach
Use configuration and platform‑neutral constructs:
String logDir = System.getProperty("app.log.dir", "/var/log/myapp");
Path logPath = Paths.get(logDir, "app.log");
Files.newBufferedWriter(logPath, StandardOpenOption.CREATE, StandardOpenOption.APPEND);
You can tune the default per environment, and you avoid hard‑coding Windows‑only paths.
Wrong path separators
Java is forgiving with / on Windows, but some code still mixes separators or builds paths manually:
String path = "data" + "\\" + "input.txt"; // yikes
File file = new File(path);
This might work locally but becomes fragile. The modern way is:
Path path = Paths.get("data", "input.txt");
File file = path.toFile();
Using Paths.get avoids subtle examples of file not found error examples in Java that only appear when you move between Windows, macOS, and Linux.
Examples include permission issues disguised as FileNotFoundException
Not every FileNotFoundException means the file is literally missing. Sometimes Java reports a file not found error when the underlying problem is permissions.
Consider a microservice trying to read a secret file:
File keyFile = new File("/etc/ssl/private/service.key");
try (FileInputStream fis = new FileInputStream(keyFile)) {
// use key
}
On a development machine where you run as an admin user, it works. On a locked‑down production box, you see:
java.io.FileNotFoundException: /etc/ssl/private/service.key (Permission denied)
The message still says FileNotFoundException, but the detail is Permission denied. This is a real example of how developers misread the exception and start searching for missing files instead of checking file ownership and access rights.
Security‑focused organizations (including U.S. government security guidance like NIST at https://csrc.nist.gov/) strongly encourage running services with minimal permissions. That makes these permission‑driven file not found errors more common in 2024–2025 than they were a decade ago.
Debugging tip
Log both the exception type and the message:
catch (FileNotFoundException e) {
logger.error("Failed to open file: {} - {}", file.getAbsolutePath(), e.getMessage());
}
The message often reveals whether this example of a file not found error in Java is about permissions, missing directories, or something else.
CI and testing: examples of file not found error examples in Java unit tests
Continuous integration systems are a gold mine of file path mistakes. A typical JUnit test might do this:
@Test
void loadsSampleJson() throws IOException {
File file = new File("src/test/resources/sample.json");
try (FileReader reader = new FileReader(file)) {
// parse JSON
}
}
On the developer machine, where the working directory is the project root, the test passes. On a CI server or when run from a different module, it fails with FileNotFoundException.
Better testing pattern
Use the test class’s classloader:
@Test
void loadsSampleJson() throws IOException {
try (InputStream is = getClass().getResourceAsStream("/sample.json")) {
assertNotNull(is, "sample.json must be on test classpath");
// parse JSON from stream
}
}
This pattern makes tests more portable and avoids brittle path assumptions. It’s one of the best examples of file not found error examples in Java that only appear when you finally wire up CI.
Container and cloud deployment: modern real examples
In 2024–2025, a lot of Java runs in containers or serverless environments. That introduces new examples of file not found error examples in Java that simply didn’t exist when everything was a bare VM.
Example: writing to a non‑existent directory in a container
Inside a Docker container, your code might try to write logs here:
File logFile = new File("/var/log/myapp/app.log");
try (FileWriter writer = new FileWriter(logFile, true)) {
writer.write("hello\n");
}
If /var/log/myapp doesn’t exist in the image, you get:
java.io.FileNotFoundException: /var/log/myapp/app.log (No such file or directory)
Notice: the directory is missing, not just the file.
Fix
Create directories before writing:
File logFile = new File("/var/log/myapp/app.log");
File parent = logFile.getParentFile();
if (!parent.exists() && !parent.mkdirs()) {
throw new IOException("Failed to create log directory: " + parent);
}
In orchestrated environments like Kubernetes, it’s common to mount volumes or config maps. Misconfigured mounts are another real example of a file not found error in Java: the code expects /config/app.yaml, but the volume was mounted at /etc/app/config.yaml.
Cloud providers and security guidelines (for example, general cloud security best practices from NIST at https://www.nist.gov/topics/cloud-computing) encourage immutable containers, so you’ll see more read‑only file systems and stricter volume mounting. That means more of these examples of file not found error examples in Java unless paths and mounts are carefully documented.
Diagnosing file not found: patterns and best practices
After you’ve seen enough examples of file not found error examples in Java, a few patterns emerge:
- Relative vs absolute paths: Most bugs come from assuming the working directory. Log
new File(path).getAbsolutePath()when debugging. - Classpath vs file system: If the file ships with the application, treat it as a resource, not a disk file.
- Environment‑specific configuration: Paths that work on a laptop rarely match production or containers unless they’re configurable.
- Permissions and directories: A missing parent directory or denied access often bubbles up as FileNotFoundException.
Here is a small utility style that helps avoid many of these examples:
public final class FileUtils {
private FileUtils() {}
public static InputStream openRequiredResource(String resourcePath) throws IOException {
InputStream is = FileUtils.class.getResourceAsStream(resourcePath);
if (is == null) {
throw new FileNotFoundException("Resource not found on classpath: " + resourcePath);
}
return is;
}
public static BufferedReader openRequiredFile(Path path) throws IOException {
if (!Files.exists(path)) {
throw new FileNotFoundException("File does not exist: " + path.toAbsolutePath());
}
if (!Files.isReadable(path)) {
throw new FileNotFoundException("File not readable: " + path.toAbsolutePath());
}
return Files.newBufferedReader(path);
}
}
By centralizing checks like this, you get consistent error messages and fewer mysterious examples of file not found error examples in Java scattered throughout your codebase.
For broader secure‑coding guidance, OWASP’s documentation is worth a read: https://owasp.org/.
FAQ: common questions about Java file not found errors
What are common examples of FileNotFoundException in Java applications?
Common examples of FileNotFoundException in Java include missing config files referenced with relative paths, JAR‑packaged resources incorrectly opened via File, Windows‑only paths used on Linux servers, CI tests that assume a specific working directory, and containerized apps writing to directories that don’t exist or aren’t mounted.
Can you show a simple example of fixing a file not found error in Java?
A simple example of fixing a file not found error in Java is replacing:
FileInputStream fis = new FileInputStream("config.properties");
with:
try (InputStream is = App.class.getResourceAsStream("/config.properties")) {
if (is == null) {
throw new IllegalStateException("config.properties missing from classpath");
}
// load properties
}
That single change often fixes file not found issues when moving from an IDE run to a packaged JAR.
How do I debug intermittent file not found errors that only happen in production?
Log the absolute path, the current working directory, and the user the process runs as. Many real examples of file not found error examples in Java turn out to be environment mismatches: different working directory, missing mount, or stricter permissions. Reproduce the production environment locally or in a staging container to confirm.
Are file not found errors always fatal?
Not necessarily. For optional features (like an override config file), you can treat a file not found error as “feature disabled” and continue. For required files (keys, schemas, core configs), it’s usually better to fail fast with a clear message so operators know exactly which path failed.
The bottom line: once you’ve seen enough examples of file not found error examples in Java across local development, CI, containers, and production, you start to recognize the same patterns repeating. Use classpath resources for bundled files, configuration for environment‑specific paths, and the NIO API for safer path handling. Your logs will be quieter, and your future self will thank you.
Related Topics
Real-world examples of file not found error examples in Node.js
Practical examples of file not found error examples in Java (and how to fix them)
The best examples of file not found error examples in HTML linking (and how to fix them)
Real-world examples of resolving file not found error in Linux
Modern examples of File Not Found exception handling in real code
Examples of File Not Found Error in Python: 3 Practical Examples (Plus More You Actually See)
Explore More File Not Found Errors
Discover more examples and insights in this category.
View All File Not Found Errors