The pipeline in Java NIO is similar to the actual pipeline, with two ends, one section as input and the other section as output. That is to say, after creating a pipeline, you can write the pipeline or read the pipeline, but these two operations must be performed at both ends. A bit like a queue.
Here is a diagram of the Pipe principle:
Create a pipeline
Open the pipeline via the Pipe.open() method. For example:
Pipe pipe = Pipe.open();
Write data to the pipeline
To write data to the pipeline, you need to access the sink channel. Like this:
Pipe.SinkChannel sinkChannel = pipe.sink();
Write data to SinkChannel by calling the write() method of SinkChannel, like this:
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);}In the test example, we give a very simple pipeline operation, first write content to the pipeline, and then read content from the pipeline.
package com.test.nio;import java.io.IOException;import java.nio.ByteBuffer;import java.nio.channels.Pipe;public class TestPipeA {/** * @param args * @throws Exception */public static void main(String[] args) throws Exception {//Create a pipeline Pipe pipe=Pipe.open();//Create a write pipeline Pipe.SinkChannel sinkChannel=pipe.sink();String newData="itbuluoge.com says:"+System.currentTimeMillis();ByteBuffer buf=ByteBuffer.allocate(48);buf.clear();buf.put(newData.getBytes());buf.flip();/*Write content to the pipeline*/while(buf.hasRemaining()) {sinkChannel.write(buf);}/*Create a read pipeline*/Pipe.SourceChannel sourceChannel=pipe.source();ByteBuffer getBuf=ByteBuffer.allocate(48);int bytesRead=sourceChannel.read(getBuf);getBuf.flip();/*Read content from the pipeline*/while(getBuf.hasRemaining()) {System.out.print((char)getBuf.get());}}}Output result
We can see that we can achieve the goals we need. Note that when I was programming in this place, I had an error, that is, when I was reading the pipeline, I did not set getBuf.flip(), which made it impossible to read the data. This function is very important. After completing the buffer reading content, you must set the read flag and restore the pointer to the original position before you can read all the content.
The above is all the content shared in this article about the usage code of java NIO pipelines, and I hope it will be helpful to everyone. Interested friends can continue to refer to other related topics on this site. If there are any shortcomings, please leave a message to point it out. Thank you friends for your support for this site!