Java NIO Pipe

Java NIO Pipe是两个线程之间的单向数据连接。 Pipe(管道)具有 source channel(源通道) 和 sink channel(接收器通道) 。 你将数据写入接收器通道,然后可以从源通道读取该数据。

示意图如下:

pipe-internals

基本用法

创建Pipe

直接调用 open() 方法创建 Pipe. 如下:

1
Pipe pipe = Pipe.open();

写入Pipe

数据先要写入到sink channel,因此先要获取sink channel.

1
Pipe.SinkChannel sinkChannel = pipe.sink();

写入 sinkChannel(),如下:

1
2
3
4
5
6
7
8
9
10
11
String newData = "New String to write to file..." + System.currentTimeMillis();

ByteBuffer buf = ByteBuffer.allocate(48);
buf.clear();
buf.put(newData.getBytes());

buf.flip();

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

读取Pipe

从Pipe中读取数据,先要获取 soucechannel。如下:

1
Pipe.SourceChannel sourceChannel = pipe.source();

调用 read() 方法从 sorce channel 中读取数据,如下:

1
2
3
ByteBuffer buf = ByteBuffer.allocate(48);

int bytesRead = inChannel.read(buf);

返回的 int 数据,表示已有多少bytes读到buffer中去了。

示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
package one.wangwei.java.nio;

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

public class PipeExample {

public static void main(String[] args) {
try {
//The Pipe is created
Pipe pipe = Pipe.open();
//For accessing the pipe sink channel
Pipe.SinkChannel skChannel = pipe.sink();
String td = "Data is successfully sent for checking the java NIO Channel Pipe.";
ByteBuffer bb = ByteBuffer.allocate(512);
bb.clear();
bb.put(td.getBytes());
bb.flip();
//write the data into a sink channel.
while (bb.hasRemaining()) {
skChannel.write(bb);
}
//For accessing the pipe source channel
Pipe.SourceChannel sourceChannel = pipe.source();
bb = ByteBuffer.allocate(512);
//The data is write to the console
while (sourceChannel.read(bb) > 0) {
bb.flip();
while (bb.hasRemaining()) {
char TestData = (char) bb.get();
System.out.print(TestData);
}
bb.clear();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}

参考资料

请我喝杯咖啡吧~