Pipe

2018-12-27  本文已影响0人  JiinYuu

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

下图展示了Pipe的原理:

Java NIO:Pipe的内部组成

Creating a Pipe

通过调用Pipe.open()方法,你可以打开一个Pipe。就像下面这样:

Pipe pipe = Pipe.open();

Write to a Pipe

为了向Pipe写入数据,你需要先获取sink channel,就像这样:

Pipe.SinkChannel sinkChannel = pipe.sink();

然后通过调用SinkChannelwrite()方法向其写入数据,就像这样:

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

然后通过调用SourceChannelread()方法来读取数据,就像这样:

ByteBuffer buffer = ByteBuffer.allocate(48);
int bytesRead = sourceChannel.read(buffer);

read()方法返回的int就代表着有多少数据被读入了Buffer

发现貌似有人在看这个系列文章了,有必要说明下,这个Java NIO系列来源于jenkov.com,本文只是翻译,希望大家千万不要误会,本文不是原创。原文地址:Java NIO

上一篇 下一篇

猜你喜欢

热点阅读