Java NIO管道

Java NIO管道用于在两个线程之间建立单向数据连接。它有一个槽通道和源通道。数据正在写入槽通道,然后可以从源通道读取该数据。

在Java NIO中,包java.nio.channel.pipe用于按顺序读取和写入数据。管道用于确保数据必须以写入管道的相同顺序读取。

下面来看看管道工作原理的示意图说明:

创建管道

要创建一个管道,可通过调用Pipe.open()方法打开管道。

打开或创建管道的语法是:

Pipe pp = Pipe.open();
Java

从管道读取数据

要从管道读取数据,需要先访问源通道。 因此,用于访问源通道的语法是:

Pipe.SourceChannel sc= pipe.source();
Java

要从SourceChannel读取数据,可调用read()方法,如下所示:

ByteBuffer bb= ByteBuffer.allocate(512);  
int bytesRead = inChannel.read(bb);
Java

read()方法返回的整数值用于确定读入缓冲区的字节数。

写入管道

要将数据写入管道,需要访问接收器通道。访问宿通道的语法是:

Pipe.SinkChannel sc= pipe.sink();
Java

要将数据写入SinkChannel,可调用write()方法,如下所示:

String newData = "The new String is writing in a Pipe..." + System.currentTimeMillis();  
ByteBuffer bb= ByteBuffer.allocate(512);  
bb.clear();  
bb.put(newData.getBytes());  
bb.flip();  
while(bb.hasRemaining()) {  
    SinkChannel.write(bb);  
}
Java

基本管道示例:

package com.yiibai;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.Pipe;

public class PipeExample {
    public static void main(String[] args) throws IOException {
        // The Pipe is created
        Pipe pipe = Pipe.open();
        // For accessing the pipe sink channel
        Pipe.SinkChannel skChannel = pipe.sink();
        String td = "Data is successfully sent for checking the java NIO Channel Pipe.";
        ByteBuffer bb = ByteBuffer.allocate(512);
        bb.clear();
        bb.put(td.getBytes());
        bb.flip();
        // write the data into a sink channel.
        while (bb.hasRemaining()) {
            skChannel.write(bb);
        }
        // For accessing the pipe source channel
        Pipe.SourceChannel sourceChannel = pipe.source();
        bb = ByteBuffer.allocate(512);
        // The data is write to the console
        while (sourceChannel.read(bb) > 0) {
            bb.flip();

            while (bb.hasRemaining()) {
                char TestData = (char) bb.get();
                System.out.print(TestData);
            }
            bb.clear();
        }
    }
}
Java

执行上面示例代码,得到以下结果 -


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值