首页
学习
活动
专区
圈层
工具
发布
社区首页 >专栏 >Java NIO-2.Channel

Java NIO-2.Channel

作者头像
悠扬前奏
发布于 2019-06-02 12:55:40
发布于 2019-06-02 12:55:40
5990
举报

Java NIO 的Channels和流(stream)很像,但是有如下区别:

  • Channels既能读又能写,Stream只能读或者写
  • Channels能异步读写
  • Channels只能读到Buffer中,或者从Buffer写入

Channel实例

以下是Java NIO中重要的的Channel实例:

  • FileChannel:从/往文件中读/写
  • DatagramChannel:通过UDP读写网络数据
  • SocketChannel:通过TCP读写网络数据
  • ServerSocketChannel:监听接入的TCP连接,就像web服务器那样。对于每个接入进来的TCP连接都创建一个SocketChannel

基础Channel例子

以下是一个例子,通过FileChannel往Buffer中读一些数据:

代码语言:javascript
复制
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);

文件nio-data.txt:

代码语言:javascript
复制
1234567890
1234567890
1234567890
1234567890
1234567890
1234567890

输出结果为:

代码语言:javascript
复制
Read 48
1234567890
1234567890
1234567890
1234567890
1234Read 17
567890
1234567890
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2018.05.31 ,如有侵权请联系 cloudcommunity@tencent.com 删除
目录
  • Channel实例
  • 基础Channel例子
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档