⚙️ Let’s break down the difference between IO (java.io) and NIO (java.nio) — two major APIs for handling input/output in Java.
✅ TL;DR: Main Differences
Feature | IO (java.io) | NIO (java.nio) |
---|
Type | Stream-oriented (blocking) | Buffer-oriented (non-blocking capable) |
Blocking? | Always blocking | Can be non-blocking (with Selectors) |
Data Access | Sequential | Random access (via FileChannel ) |
Performance | Slower for large data | Faster, especially with large or concurrent I/O |
Selectors/Channels | ❌ Not available | ✅ Available — great for scalable network I/O |
Introduced in | Early Java versions | Java 1.4 (and improved in Java 7 with NIO.2) |
🔧 IO (java.io)
- Based on InputStream and OutputStream
- Blocking: each read/write call waits until it’s done
- Easy to use for small/simple file and stream operations
✅ Example:
FileInputStream in = new FileInputStream("file.txt");
int data = in.read(); // blocks until data is read
🚀 NIO (java.nio)
- Based on Channels and Buffers
- Uses Selectors for multiplexed, non-blocking I/O
- Much better for scalable servers, network apps, and performance
✅ Example:
RandomAccessFile file = new RandomAccessFile("file.txt", "r");
FileChannel channel = file.getChannel();
ByteBuffer buffer = ByteBuffer.allocate(1024);
channel.read(buffer); // fills buffer with data
🔥 NIO.2 (Java 7+)
- Introduced
java.nio.file.*
package - Added Paths, Files, WatchService (directory monitoring), better file operations
✅ NIO.2 Example:
Path path = Paths.get("file.txt");
List<String> lines = Files.readAllLines(path);
🧠 Summary
Use IO when… | Use NIO when… |
---|
Simpler, small file I/O | High-performance or scalable I/O |
Blocking behavior is okay | You need non-blocking I/O (e.g., sockets) |
You want simplicity | You need power, flexibility, and performance |