Back to Lessons

File Input Output Operations

April 5, 2026

Java File I/O

Read and write files using streams and NIO.2.

File Operations

import java.io.*;
import java.nio.file.*;

// Traditional I/O
try (BufferedWriter writer = new BufferedWriter(new FileWriter("data.txt"))) {
    writer.write("Hello File");
} catch (IOException e) {
    e.printStackTrace();
}

// NIO.2
Files.write(Paths.get("data.txt"), "Hello NIO".getBytes());

Key Points

  • Try-with-resources auto-closes streams.
  • Buffered streams more efficient.
  • NIO.2 Path/Files for modern file operations.
  • Handle IOException properly.