7. Java NIO系列之管道Pipe

来源:互联网 发布:苏州相城淘宝培训 编辑:程序博客网 时间:2024/04/29 02:59

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

import java.io.IOException;import java.nio.ByteBuffer;import java.nio.channels.Pipe;import org.junit.Test;public class TestPipe {@Testpublic void test1() throws IOException{//1. 获取管道Pipe pipe = Pipe.open();//2. 将缓冲区中的数据写入管道ByteBuffer buf = ByteBuffer.allocate(1024);Pipe.SinkChannel sinkChannel = pipe.sink();buf.put("通过单向管道发送数据".getBytes());buf.flip();sinkChannel.write(buf);//3. 读取缓冲区中的数据Pipe.SourceChannel sourceChannel = pipe.source();buf.flip();int len = sourceChannel.read(buf);System.out.println(new String(buf.array(), 0, len));sourceChannel.close();sinkChannel.close();}}


0 0
原创粉丝点击