11、NIO--管道Pipe

管道(Pipe)

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

@Test
    public void test() throws IOException{
        //1、获取管道
        Pipe pipe = Pipe.open();
        
        //2、将缓冲区的数据写入管道
        ByteBuffer buf = ByteBuffer.allocate(1024);
        
        Pipe.SinkChannel sinkChannel = pipe.sink();
        buf.put("MrChegns".getBytes());
        buf.flip();
        sinkChannel.write(buf);
        
        //3、读取缓冲区中的信息
        Pipe.SourceChannel sourceChannel = pipe.source();
        buf.flip();
        sourceChannel.read(buf);
        
        System.out.println(new String(buf.array(),0,buf.limit()));
        
        //4、关闭
        sourceChannel.close();
        sinkChannel.close();
    }

 

实例:

向管道中写数据

从管道中读取数据

原文地址:https://www.cnblogs.com/Mrchengs/p/10841707.html