前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Java NIO-11.管道

Java NIO-11.管道

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

Java NIO管道(Pipe)是两个进程间的单向连接。管道有一个源通道和一个sink通道,往sink通道中写数据,数据就能从source通道中读取。

Pipe Internals

创建管道

调用Pipe.open()方法就能打开一个Pipe:

Pipe pipe = Pipe.open()

往Pipe中写

往Pipe中写,需要访问sink通道,例如:

Pipe.SinkChannel sinkChannel = pipe.sink();

调用SinkChannel的write()方法就能往里面写数据了,例如:

String newData = "New String to write to file..." + System.currentTimeMillis();

ByteBuffer buf = ByteBuffer.allocate(48);
buf.clear();
buf.put(newData.getBytes());

buf.flip();

while(buf.hasRemaining()) {
    sinkChannel.write(buf);
}

从Pipe中读

读Pipe需要访问source通道,就像这样:

Pipe.SourceChannel sourceChannel = pipe.source();

调用source通道的read()方法可以读取里面的数据,例如:

ByteBuffer buf = ByteBuffer.allocate(48);
int bytesRead = inChannel.read(buf);

read()方法返回的int表示读了多少字节的数据到缓冲区中。

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2018.06.04 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 创建管道
  • 往Pipe中写
  • 从Pipe中读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档