Java NIO Pipeline

Source: Internet
Author: User

Piping (pipe)
(This part of the original link, Jakob Jenkov, translator: Jack Huang, proofreading: Ding)
The Java NIO pipeline is a one-way data connection between 2 threads. The pipe has a source channel and a sink channel. The data is written to the sink channel, which is read from the source channel.

Here is the diagram of the pipe principle:



Creating Pipelines

Open the pipeline through the Pipe.open () method. For example:

Java code
    1. Pipe pipe = Pipe.open ();


write data to the pipeline

To write data to the pipeline, you need access to the sink channel. Like this:

Java code
    1. Pipe.sinkchannel Sinkchannel = Pipe.sink ();


By calling Sinkchannel's write () method, the data is written to Sinkchannel, like this:

Java code
    1. String NewData = "New String to write to file ..." + System.currenttimemillis ();
    2. Bytebuffer buf = bytebuffer.allocate (48);
    3. Buf.clear ();
    4. Buf.put (Newdata.getbytes ());
    5. Buf.flip ();
    6. while (Buf.hasremaining ()) {
    7. <b>sinkchannel.write (BUF);</b>
    8. }


reading data from a pipeline

From reading the data of the pipeline, you need to access the source channel, like this:

Java code
    1. Pipe.sourcechannel Sourcechannel = Pipe.source ();


Call the source channel's read () method to read the data, like this:

Java code
    1. Bytebuffer buf = bytebuffer.allocate (48);
    2. int bytesread = Inchannel.read (BUF);


The int value returned by the Read () method tells us how many bytes were read into the buffer.

Java NIO Pipeline

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.