Java NIO Pipe

Java NIO Pipe是两个线程之间的单向数据连接,Pipe具有source channelsink channel。写数据到sink channel,然后可以从source channel读取此数据。

这是Pipe原理的说明:

pipe-internals.png

 

 

1.创建Pipe

可以通过调用Pipe.open()方法来打开Pipe:

Pipe pipe = Pipe.open();

 

2.写数据到Pipe

要写入Pipe,需要访问sink channel

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);
}

 

3.从Pipe读取

要从管道读取,需要访问source channel

Pipe.SourceChannel sourceChannel = pipe.source();

 

要从source channel读取,可以调用其read()方法:

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

 

read()方法返回的int表面已将多少字节读取到缓冲区中。

 

原文地址: https://www.zhblog.net/go/java/tutorial/java-nio-pipe?t=622

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值