Java NIO深入理解Pipe(管道) - Go语言中文社区

Java NIO深入理解Pipe(管道)


前言

Github:https://github.com/yihonglei/java-all

Project:java-nio

一 Java NIO概述

Java NIO 管道是2个线程之间的单向数据连接。Pipe有一个source通道和一个sink通道。

数据会被写到sink通道,从source通道读取。Pipe原理图:

 

二 创建管道

通过Pipe.open()方法打开管道。示例:

Pipe pipe = Pipe.open();

三 向管道写数据

要向管道写数据,需要访问sink通道。示例:

Pipe.SinkChannel sinkChannel = pipe.sink();

通过调用SinkChannel的write()方法,将数据写入SinkChannel,示例:

String newData = "测试文件写入数据" + System.currentTimeMillis();

ByteBuffer buf = ByteBuffer.allocate(48);

buf.clear();

buf.put(newData.getBytes());

buf.flip();

while(buf.hasRemaining()) {

    sinkChannel.write(buf);

}

四 从管道读取数据

从读取管道的数据,需要访问source通道,示例:

Pipe.SourceChannel sourceChannel = pipe.source();

调用source通道的read()方法来读取数据,示例:

ByteBuffer buf = ByteBuffer.allocate(48);

int bytesRead = sourceChannel.read(buf);

read()方法返回的int值会告诉我们多少字节被读进了缓冲区。

五 完整实例

package com.lanhuigu.nio.pipe;


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

/**
 * @author yihonglei
 */
public class PipeTest {
    public static void main(String[] args) throws IOException {
        // 1. 获取管道
        Pipe pipe = Pipe.open();

        // 2. 将缓冲区数据写入到管道
        // 2.1 获取一个通道
        Pipe.SinkChannel sinkChannel = pipe.sink();
        // 2.2 定义缓冲区
        ByteBuffer buffer = ByteBuffer.allocate(48);
        buffer.put("发送数据".getBytes());
        buffer.flip(); // 切换数据模式
        // 2.3 将数据写入到管道
        sinkChannel.write(buffer);

        // 3. 从管道读取数据
        Pipe.SourceChannel sourceChannel = pipe.source();
        buffer.flip();
        int len = sourceChannel.read(buffer);
        System.out.println(new String(buffer.array(), 0, len));

        // 4. 关闭管道
        sinkChannel.close();
        sourceChannel.close();
    }
}

 

版权声明:本文来源CSDN,感谢博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
原文链接:https://blog.csdn.net/yhl_jxy/article/details/79336762
站方申明:本站部分内容来自社区用户分享,若涉及侵权,请联系站方删除。
  • 发表于 2020-03-07 16:14:42
  • 阅读 ( 1638 )
  • 分类:Go深入理解

0 条评论

请先 登录 后评论

官方社群

GO教程

猜你喜欢