NiO pipeline usage code sharing of Java

The pipeline in Java NiO is similar to the actual pipeline. It has two ends, one as input and one as output. In other words, after creating a pipe, you can write to or read from the pipe, but the two operations should be carried out at both ends respectively. It's a bit like a queue.

Here is an illustration of pipe principle:

Create pipe

Through pipe The open () method opens the pipe. For example:

Pipe pipe = Pipe. open();

Write data to pipeline

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

Pipe. SinkChannel sinkChannel = pipe. sink();

Write data to the sinkchannel by calling the write() method of the sinkchannel, as follows:

In the test example, we give a very simple pipeline operation, first write the content to the pipeline, and then read the content from the pipeline.

Output results

We can see that we can achieve the goals we need. Note that I made an error when programming in this place, that is, when I read the pipeline, I did not set getbuf Flip(), which makes it impossible to read data. This function is very important. After the buffer reads the 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 about the sharing of NiO pipeline usage code of Java in this article. I hope it will be helpful to you. Interested friends can continue to refer to other related topics on this site. If there are deficiencies, please leave a message to point out. Thank you for your support!

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>