Java NIO Channel

Channel is a stream kind of representation in NIO. It is a representation of hardware, file, network device or other program.

There are several different channel that loads data differently.

  • FileChannel
  • DatagramChannel
  • SocketChannel
  • ServerSocketChannel

Unlike stream object, which can only input or output one at a time. A single Channel object can do both read and write simutanously.

1
2
3
4
5
6
7
8
try (RandomAccessFile file = new RandomAccessFile("data.md", "rw");
FileChannel c = file.getChannel()) {
final ByteBuffer b = ByteBuffer.allocate(64);
b.clear();
System.out.println("Read " + c.read(b));
b.flip();
System.out.println("Write " + c.write(b));
}

From the snippet above, we can tell that a single channel object can do both read and write.


Java NIO Channel
https://rug.al/2020/2020-03-08-java-nio-channel/
Author
Rugal Bernstein
Posted on
March 8, 2020
Licensed under