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();}