🧠 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 |
✅ What is a Channel?
In Java NIO, a Channel is like a modern alternative to InputStream
/OutputStream
, but more powerful.
It represents a connection to a data source (like a file, socket, etc.), through which you can read, write, or both.
🔹 Key Features of Channels:
Feature | Description |
---|---|
Bi-directional | Some channels can read and write (e.g. SocketChannel ) |
Non-blocking | Channels can be used with selectors for non-blocking I/O |
Used with Buffers | You read data into a buffer, not directly |
Faster than streams | Because of direct memory access, better for large files |
✅ Example: Reading with a FileChannel
RandomAccessFile file = new RandomAccessFile("data.txt", "r");
FileChannel channel = file.getChannel();
ByteBuffer buffer = ByteBuffer.allocate(1024);
channel.read(buffer); // data is now in buffer
✅ What is Random Access?
Random Access means you can jump to any position in a file and read/write from there — not just sequentially from start to end.
🔹 In Java: RandomAccessFile
RandomAccessFile raf = new RandomAccessFile("data.txt", "rw");
raf.seek(100); // move to byte 100
raf.writeByte(42); // overwrite that byte
🔹 With FileChannel
FileChannel channel = raf.getChannel();
channel.position(200); // jump to byte 200
channel.write(ByteBuffer.wrap("Hi".getBytes()));
✅ When Random Access Is Useful
- Editing files without reading the whole thing
- Working with large files (logs, databases)
- Implementing custom file-based structures like indexes or data blocks
🧠 Summary
Concept | Description |
---|---|
Channel | NIO abstraction to read/write data from files/sockets/etc. |
Random Access | Ability to move to any position in the file and read/write |