Pipe

作者: JiinYuu | 来源:发表于2018-12-27 16:05 被阅读0次

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

相关文章

  • 聊聊storagetapper的pipe

    序 本文主要研究一下storagetapper的pipe Pipe storagetapper/pipe/pipe...

  • NIO十二-Pipe

    Java NIO Pipe Creating a Pipe Writing to a Pipe Reading f...

  • Angular Pipe

    Angular Pipe is object, not function, when pipe created, ...

  • python 学习笔记(Queue & Pipe 进程间的通讯)

    Pipe multiprocessing.Pipe()即管道模式,调用Pipe()返回管道的两端的Connecti...

  • 自定义pipe

    自定义pipe pipe说明:(自定义pipe只需实现 PipeTransform接口的transform方法即可 )

  • Linux IPC

    Pipe Named Pipe Signal Semaphore Message Queue Memory Sha...

  • Linux IPC

    Pipe/FIFO(named Pipe)/Semaphore/Message Queue/Share Memor...

  • 管道

    man 7 PIPE pipe和FIFO介绍pipe匿名管道,只能用于有亲缘关系的进程间通信FIFO命名管道,任意...

  • Android进程间通信机制-管道

    PIPE和FIFO的使用及原理 PIPE和FIFO都是指管道,只是PIPE独指匿名管道,FIFO独指有名管道,我们...

  • ng2 内置pipe 一览

    ng2 内置pipe 一览 pipe说明: UpperCasePipe --- Transforms text ...

网友评论

      本文标题:Pipe

      本文链接:https://www.haomeiwen.com/subject/zmarlqtx.html