Java NIO channels are similar to streams, but different:

  • You can read data from a channel and write data to a channel. But reads and writes to streams are usually one-way
  • Channels can be read and written asynchronously
  • Data in a channel is always read to or written to from a Buffer.

Read data from Channel to buffer and write data from buffer to Channel.

The realization of the Channel

Implementation of the most important channels in Java NIO:

  • FileChannel

Reads and writes data from a file.

  • DatagramChannel

Read and write data on the network through UDP.

  • SocketChannel

Read and write data on the network through TCP.

  • ServerSocketChannel

Listen for incoming TCP connections, just like a Web server. A SocketChannel is created for each incoming connection.

The Channel sample

Here is an example of reading data into a Buffer using FileChannel:

RandomAccessFile aFile = new RandomAccessFile("data/nio-data.txt"."rw");
FileChannel inChannel = aFile.getChannel();

ByteBuffer buf = ByteBuffer.allocate(48);

int bytesRead = inChannel.read(buf);
while(bytesRead ! = -1) {
  System.out.println("Read " + bytesRead);
  buf.flip();

  while(buf.hasRemaining()){
      System.out.print((char) buf.get());
  }

  buf.clear();
  bytesRead = inChannel.read(buf);
}
aFile.close()
Copy the code

Note that buf.flip() first reads data into Buffer, then reverses Buffer, and then reads data from Buffer.

reference

  • Tutorials.jenkov.com/java-nio/ch…