文章目录



一、简介


​Channel​​: 用于在字节缓冲区和位于通道另一侧的实体 (通常是一个文件或套接字) 之间有效地传输数据

​Channel​​实现有:

  • FileChannel: 从文件中读写数据
  • DatagramChannel: 能通过 UDP 读写网络中的数据
  • SocketChannel: 能通过 TCP 读写网络中的数据
  • ServerSocketChannel: 可以监听 TCP 连接, 对每一个新进来的连接都会创建一个 SocketChannel



二、使用


ByteBuffer buf = ByteBuffer.allocate(1024);

int bytesRead = inChannel.read(buf);

while(bytesRead != -1) {
buf.flip();

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

buf.clear();
bytesRead = inChannel.read(buf);
}




三、参考资料


  1. ​http://ifeve.com/channels/​
  2. << Java NIO >>