美文网首页
Java NIO(8) - 管道

Java NIO(8) - 管道

作者: 21号新秀_邓肯 | 来源:发表于2020-05-15 11:24 被阅读0次

5.管道(Pipe)

Java NIO 管道是2个线程之间的单向数据连接。Pipe有一个source通道和一个sink通道。数据会被写到sink通道,从source通道读取

image.png

5.1 向管道写数据

    public void test01() throws IOException {
        String str = "测试数据";

        //创建管道
        Pipe pipe = Pipe.open();

        //向管道写输入
        Pipe.SinkChannel sinkChannel = pipe.sink();

        //通过 SinkChannel 的write() 方法写数据
        ByteBuffer buf = ByteBuffer.allocate(1024);
        buf.clear();
        buf.put(str.getBytes());

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

5.2 向管道读数据

    public void test02() throws IOException {
        //创建管道
        Pipe pipe = Pipe.open();

        //从管道读取数据
        Pipe.SourceChannel sourceChannel = pipe.source();

        //调用 SourceChannel 的 read() 方法取数据
        ByteBuffer buf = ByteBuffer.allocate(1024);
        sourceChannel.read(buf);
    }

相关文章

网友评论

      本文标题:Java NIO(8) - 管道

      本文链接:https://www.haomeiwen.com/subject/xftcohtx.html