NIO--管道(Pipe)

管道(Pipe)

Java NIO管道是2个线程之间的单向数据连接。

Pipe有一个source通道和一个 sink通道。数据会被写到sink通道,从source通道读取。

在这里插入图片描述

向管道写数据

@Test
public void test() thorws 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());
	buf.flip();

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

从管道读数据

从读取管道的数据,需要访问source通道。

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

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

//调用SourceChannel的read()方法读取数据
ByteBuffer buf = ByteBuffer.allocate(1024);
sourceChannel.read(buf);
发布了766 篇原创文章 · 获赞 2129 · 访问量 26万+

猜你喜欢

转载自blog.csdn.net/cold___play/article/details/104321270