5. Transmission of data between different channel channel
In Java NiO, if one of the two channels is filechannel, then we can transfer the data directly from one channel to another channel. There are two different ways to transfer data between two channels, respectively:
-Transferfrom ()
-TransferTo () 5.1 transferfrom ( )
The filechannel Transferfrom () method transmits data from the source channel to the FileChannel (this method is interpreted in the JDK documentation as transferring bytes from the given readable byte channel to the file in this channel). The following is a simple example:
Randomaccessfile fromfile = new Randomaccessfile ("FromFile.txt", "RW");
FileChannel Fromchannel = Fromfile.getchannel ();//Get the channel of source;
Randomaccessfile tofile = new Randomaccessfile ("ToFile.txt", "RW");
FileChannel Tochannel = Tofile.getchannel ();//Get dest channel;
Long position = 0;
Long Count = Fromchannel.size ();
Long result = Tochannel.transferfrom (Fromchannel, position, count);
Logutil.log_debug ("" +result);
Input parameters of the method
-position indicates that data is written to the target file from the position.
-count represents the maximum number of bytes transmitted. If the remaining space of the source channel is less than count bytes, the number of bytes transferred is less than the requested number of bytes.
Also note that in Soketchannel implementations, Socketchannel only transmits data that is ready at the moment (possibly less than count bytes). Therefore, Socketchannel may not transfer all of the requested data (count bytes) to FileChannel. 5.2 TransferTo () method
The TransferTo () method transmits data from FileChannel to other channel. The following is a simple example:
Randomaccessfile fromfile = new Randomaccessfile ("FromFile.txt", "RW");
FileChannel Fromchannel = Fromfile.getchannel ();//Get the channel of source;
Randomaccessfile tofile = new Randomaccessfile ("ToFile.txt", "RW");
FileChannel Tochannel = Tofile.getchannel ();//Get dest channel;
Long position = 0;
Long Count = Fromchannel.size ();
Long result = Fromchannel.transferto (position, count, Tochannel);
Logutil.log_debug ("" +result);
Observation can be found, in fact, these two examples are very similar, if only from the point of view of file Io, is the data replication between two files;
The problems mentioned above about Socketchannel are also present in the Transferto () method. Socketchannel will continue to transmit data until the target buffer is filled.