Data transfer between channels of JAVA-4NIO, java-4niochannel
Reprinted: Self-Concurrent Programming Network ifeve.com
In Java NIO, if one of the two channels is FileChannel, you can directly transmit data from one channel (Translator's note: channel's Chinese often translated channel) to another channel.
TransferFrom (): passive receiving
The transferFrom () method of FileChannel can transmit data from the source channel to FileChannel: this method is interpreted in the JDK document as transmitting bytes from a given readable byte channel to a file in this channel ).
The input parameter position of the method indicates that data is written to the target file starting from position, and count indicates the maximum number of bytes transmitted. If the remaining space of the source channel is smaller than count bytes, the number of bytes transmitted is smaller than the number of bytes requested.
In addition, in the SoketChannel implementation, SocketChannel only transmits the data prepared at the moment (possibly less than count bytes ). Therefore, SocketChannel may not transmit all requested data (count bytes) to the FileChannel.
TransferTo (): actively send
The transferTo () method transmits data from FileChannel to other channels. The following is a simple example:
Except for the FileChannel object of the call method, all others are the same.
The above mentioned SocketChannel problem also exists in the transferTo () method. SocketChannel will transmit data until the target buffer is filled up.
Example:
@ Test public void test2 () {RandomAccessFile fromFile = new RandomAccessFile ("fromFile.txt", "rw"); FileChannel fromChannel = fromFile. getChannel (); RandomAccessFile toFile = new RandomAccessFile ("toFile.txt", "rw"); FileChannel toChannel = toFile. getChannel (); long position = 0; long count = fromChannel. size (); // read from the from this channel; note that socketfrom will only send prepared, not count toChannel. transferFrom (fromChannel, position, count); // write the current channel to; note that sockedfrom will be sent until it is filled with fromChannel. transferTo (position, count, toChannel );}