Http://wiki.jikexueyuan.com/project/java-nio-zh/java-nio-scatter-gather.html
. Java NIO Scatter/gather
Scattering read refers to an operation that reads from a channel to write data to multiple buffer, which means that sctters represents the process of data from one channel to multiple buffer.
Gathering write is the opposite, indicating that data is written from multiple buffer to a channel.
Scatter/gather can be very useful in some scenarios, such as the need to process multiple copies of data that is transferred separately. For example, if a message contains a header and body, we may keep the header and body in separate buffer, and this separate handling of the header and body will make development more concise.
Bytebuffer Header = bytebuffer.allocate (+); Bytebuffer body = bytebuffer.allocate (1024x768= {header, Body};channel.read (Bufferarray);// Must be filled with a buffer before moving backwards to the next buffer, suitable for header-size fixed reads
Gathering writes
Bytebuffer Header = bytebuffer.allocate (+); Bytebuffer body = bytebuffer.allocate (1024x768); // write data into buffers = {header, Body};channel.write (Bufferarray);//sequentially writes the contents of the array into the channel, writes the data between position to the limit in buffer, For variable-size message
. Java NIO channel to channel transfers channels transport interface
In Java NIO if a channel is of type FileChannel, the data can be transferred directly to another channel using the Transferto and Transferfrom two methods FileChannel contains.
The Filechannel.transferfrom method transfers data from the channel source to the FileChannel:
New Randomaccessfile ("FromFile.txt", "RW"); FileChannel =new randomaccessfile ("ToFile.txt", "RW"); FileChannel = tofile.getchannel (); long position = 0; Long count = fromchannel.size (); Tochannel.transferfrom (Fromchannel, position, count);
The Transferfrom parameters position and count represent the write location of the destination file and the maximum amount of data written. If the channel source data is less than count, then the actual amount of data is transmitted. In addition, some Socketchannel implementations transmit only the data that is in the ready state, even if the Socketchannel subsequently has more data available. Therefore, the transfer process may not transmit the entire data.
Transferto method to transfer FileChannel data to another channel
New Randomaccessfile ("FromFile.txt", "RW"); FileChannel =new randomaccessfile ("ToFile.txt", "RW"); FileChannel = tofile.getchannel (); long position = 0; Long count = fromchannel.size (); Fromchannel.transferto (position, count, Tochannel);
This code is very similar to the code that was introduced before transfer, except that it is the filechannel that invokes the method.
The Socketchannel problem also exists with the implementation of Transferto.socketchannel that may only be sent after the buffer is filled and ended.
Java NIO (ii)