Java NIO Pipe是两个线程之间的单向数据连接。一个Pipe
有一个source channel和一个sink channel。你将数据写入sink channel,然后这些数据便可以从source channel中读取。
下图展示了Pipe
的原理:

Creating a Pipe
通过调用Pipe.open()
方法,你可以打开一个Pipe
。就像下面这样:
Pipe pipe = Pipe.open();
Write to a Pipe
为了向Pipe
写入数据,你需要先获取sink channel,就像这样:
Pipe.SinkChannel sinkChannel = pipe.sink();
然后通过调用SinkChannel
的write()
方法向其写入数据,就像这样:
String newData = "New String to write to file..." + System.currentTimeMillis();
ByteBuffer buffer = ByteBuffer.allocate(48);
buffer.clear();
buffer.put(newData.getBytes());
buffer.flip();
while (buffer.hasRemaining()) {
sinkChannel.write(buffer);
}
Reading from a Pipe
为了从Pipe
读取数据,你需要先获取source channel,就像这样:
Pipe.SourceChannel sourceChannel = pipe.source();
然后通过调用SourceChannel
的read()
方法来读取数据,就像这样:
ByteBuffer buffer = ByteBuffer.allocate(48);
int bytesRead = sourceChannel.read(buffer);
read()
方法返回的int
就代表着有多少数据被读入了Buffer
。
发现貌似有人在看这个系列文章了,有必要说明下,这个Java NIO系列来源于jenkov.com,本文只是翻译,希望大家千万不要误会,本文不是原创。原文地址:Java NIO。
网友评论