Reprint: Self-concurrent programming network ifeve.com
In Java NiO, if one of the two channels is FileChannel, you can transfer the data directly from one channel (translator note: Channel Chinese translation channels) to another channel.
Transferfrom (): Passive receive
The Transferfrom () method of the FileChannel can transfer data from the source channel to the FileChannel (translator Note: This method is interpreted in the JDK document as the transfer of bytes from a given readable byte channel to a file in this channel).
The input parameter of the position method means that the data is written to the destination file starting at position, and count represents the maximum number of bytes transferred. If the remaining space of the source channel is less than count bytes, the number of bytes transferred is less than the number of bytes requested.
Also note that in the Soketchannel implementation,Socketchannel only transmits the data that is prepared at this point (which may be less than count bytes). Therefore, Socketchannel may not transfer all of the requested data (count bytes) to FileChannel.
TransferTo (): Active send
The TransferTo () method transfers data from the FileChannel to other channel. The following is a simple example:
Except that the FileChannel object that invokes the method is different, the others are the same.
The above-mentioned question about Socketchannel also exists in the Transferto () method. The Socketchannel will transmit the data until the target buffer is filled .
Example:
@Test Public voidtest2 () {randomaccessfile FromFile=NewRandomaccessfile ("FromFile.txt", "RW"); FileChannel Fromchannel=Fromfile.getchannel (); Randomaccessfile ToFile=NewRandomaccessfile ("ToFile.txt", "RW"); FileChannel Tochannel=Tofile.getchannel (); LongPosition = 0; LongCount =fromchannel.size (); //from the read to this channel; note Socketfrom will only send the one that is ready and will not send countTochannel.transferfrom (Fromchannel,position, Count); //write this channel to the to; note that the sockedfrom will always be sent until the to is filledFromchannel.transferto (position, count, Tochannel); }
Data transfer between the Java-4nio channel