Getting started with NIO

zhaozj2021-02-16  79

Channel and Buffer.

The channel is an simulation of the stream in the NIO package. All data to any destination (or from any place) must pass through a Channel object. A buffer is essentially a container object. All objects sent to a channel must first be placed in the buffer; in the same manner, any data read from the channel is read into the buffer. The difference between the channel and stream is that the channel is bidirectional. Read and write is the basic process of I / O. Reading from a channel is simple: just create a buffer, then let the channel read the data to this buffer. Writings are also quite simple: create a buffer, populate it with data, and then let the channels use this data to perform a write operation. Read the file. If you use the original I / O, then we only need to create a fileInputstream and read it from it. Reading files involving three steps: (1) Get the Channel, (2) Create buffer from FileInputStream, (3) Read the data from the Channel to buffer. Below is an example of reading a file:

The first step is to get the channel. We get channel from FileInputStream:

FileInputStream Fin = New FileInputStream ("Readshow.txt"); FileChannel FC = Fin.getChannel ();

The next step is to create a buffer: bytebuffer buffer = bytebuffer.allocate (1024); Finally, you need to read the data from the channel to the buffer, as shown below: fc.read (buffer); we don't need to tell the channel to read how much data In the buffer. Each buffer has a complex internal statistical mechanism that will track how much data has been read and how many spaces can accommodate more data. Reading and writing is simpler:

Since the buffer tracks its own data, the internal loop of the CopyFile program is very simple, as shown below: fcin.read (buffer); FCOUT.WRITE (BUFFER); before reading the buffer from the input channel We call the clear () method. Similarly, before writing the buffer to the output channel, we call the FLIP () method clear () method to reset the buffer so that it can accept the read data. FLIP () method allows the buffer to write newly read data to another channel.

转载请注明原文地址:https://www.9cbs.com/read-15258.html

New Post(0)