🔧 Error Fixes
· 1 min read

Java IOException — How to Fix It


java.io.IOException: Stream closed
java.io.FileNotFoundException: /path/to/file (No such file or directory)
java.net.SocketException: Connection reset

An I/O operation (file read/write, network request, stream) failed.

Fix 1: File Not Found

// ❌ File doesn't exist
FileReader reader = new FileReader("/missing/file.txt");  // 💥

// ✅ Check first
File file = new File("/path/to/file.txt");
if (file.exists()) {
    FileReader reader = new FileReader(file);
}

Fix 2: Stream Already Closed

// ❌ Reading from a closed stream
InputStream is = new FileInputStream("data.txt");
is.close();
is.read();  // 💥 Stream closed

// ✅ Use try-with-resources
try (InputStream is = new FileInputStream("data.txt")) {
    int data = is.read();
}  // Automatically closed

Fix 3: Permission Denied

// ❌ No write permission
Files.write(Path.of("/etc/config"), data);  // 💥

// ✅ Check permissions or use a writable directory
Path path = Path.of(System.getProperty("user.home"), "config.txt");
Files.write(path, data);

Fix 4: Network IOException

// ❌ Server unreachable or connection dropped
URL url = new URL("https://api.example.com");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(5000);
conn.setReadTimeout(5000);

try {
    InputStream is = conn.getInputStream();
} catch (IOException e) {
    System.out.println("Network error: " + e.getMessage());
}

Fix 5: Encoding Issues

// ❌ Wrong encoding
new String(bytes);  // Uses platform default encoding

// ✅ Specify encoding
new String(bytes, StandardCharsets.UTF_8);

// For readers
new InputStreamReader(is, StandardCharsets.UTF_8);

Fix 6: Disk Full

// ❌ No space left on device
// ✅ Check available space
File disk = new File("/");
long freeSpace = disk.getFreeSpace();
if (freeSpace < requiredSpace) {
    throw new IOException("Not enough disk space");
}