其他分享
首页 > 其他分享> > 第五课 管道

第五课 管道

作者:互联网

Pipe管道


package NIO;

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

public class TestPipe {
	public static void main(String[] args) {
		Sink();
	}

	public static void Sink() {
		Pipe pipe = null;
		Pipe.SinkChannel sinkChannel = null;
		try {
			// 获取管道
			pipe = Pipe.open();
			// 获取Pipe内部类 SinkChannel
			sinkChannel = pipe.sink();
			// 创建缓冲区
			ByteBuffer buf = ByteBuffer.allocate(1024);
			// 将数据写入缓冲区
			buf.put("sink--发送".getBytes());
			// 转换缓冲区为读模式
			buf.flip();
			// 将缓冲区写入通道
			sinkChannel.write(buf);
			buf.clear();
			Pipe.SourceChannel sourceChannel = pipe.source();
			sourceChannel.read(buf);
			buf.flip();
			System.out.println(new String(buf.array(), 0, buf.limit()));
			buf.clear();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (sinkChannel != null) {
				try {
					sinkChannel.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
}

标签:pipe,sinkChannel,第五课,Pipe,管道,sink,缓冲区,buf
来源: https://blog.csdn.net/weixin_44782182/article/details/114167597