🔧 Error Fixes
· 1 min read

Java FileNotFoundException — How to Fix It


java.io.FileNotFoundException: config.json (No such file or directory)
java.io.FileNotFoundException: /app/data.csv (Permission denied)

Java can’t find the file at the specified path, or it exists but you don’t have permission to access it.

Fix 1: Wrong Relative Path

// ❌ Relative path depends on working directory
new FileReader("config.json");  // Looks in CWD, not project root

// ✅ Check where Java is looking
System.out.println(new File(".").getAbsolutePath());

// ✅ Use absolute path or classpath
new FileReader("/full/path/to/config.json");

Fix 2: File in Resources (Classpath)

// ❌ Using FileReader for classpath resources
new FileReader("src/main/resources/config.json");  // 💥 In JAR

// ✅ Use getResourceAsStream
InputStream is = getClass().getResourceAsStream("/config.json");
if (is == null) throw new FileNotFoundException("Resource not found");

Fix 3: File Doesn’t Exist

// ✅ Check before reading
File file = new File("data.csv");
if (!file.exists()) {
    System.out.println("File not found: " + file.getAbsolutePath());
    return;
}

Fix 4: Permission Denied

# Check file permissions
ls -la config.json

# Fix permissions
chmod 644 config.json

Fix 5: Path Separator Issues (Windows vs Linux)

// ❌ Hardcoded separator
String path = "data\\files\\config.json";  // Fails on Linux

// ✅ Use File.separator or Path
Path path = Path.of("data", "files", "config.json");