Channels, Buffers, and Non-Blocking I/O
NIO channels provide a lower-level I/O abstraction. Buffers hold data being transferred between application code and channels.
try (FileChannel channel =
FileChannel.open(Path.of("data.bin"), StandardOpenOption.READ)) {
ByteBuffer buffer = ByteBuffer.allocate(4096);
int read = channel.read(buffer);
System.out.println("Read: " + read);
}
A ByteBuffer has position, limit, capacity, and remaining bytes. Calling flip() changes a buffer from writing mode to reading mode.
Key Takeaways
- Channels transfer data through buffers.
flip()prepares a written buffer for reading.- Use NIO directly when its control is valuable; otherwise prefer higher-level abstractions.