Java NIO 管道是2个线程之间的单向数据链接。Pipe有一个source通道和一个sink通道。数据会被写到sink通道,从source通道读取。app
这里是Pipe原理的图示:测试
示例代码ui
Pipe pipe=Pipe.open();Pipe.SinkChannel sinkChannel=pipe.sink();ByteBuffer buffer = ByteBuffer.allocate(1024);buffer.put("这是一个测试程序".getBytes("UTF-8"));buffer.flip();while (buffer.hasRemaining()){ sinkChannel.write(buffer);}Pipe.SourceChannel sourceChannel=pipe.source();ByteBuffer byteBuffer = ByteBuffer.allocate(40);int bytesRead =sourceChannel.read(byteBuffer);StringBuilder sb = new StringBuilder();byte b[] =new byte[1024];while (bytesRead !=-1){ byteBuffer.flip(); int index = 0; while (byteBuffer.hasRemaining()) { b[index++] = byteBuffer.get(); if (index >= bytesRead) { index = 0; sb.append(new String(b, "UTF-8")); System.out.println(sb.toString()); } } byteBuffer.clear();}