Java NIO Channel to channel transfers
In Java NIO can transfer data directly from one channel to another, if one of the channels is a FileChannel . The FileChannel class has a and transferTo() a transferFrom() method which does.
Transferfrom ()
The FileChannel.transferFrom() method transfers data from a source channel into the FileChannel . Here are a simple example:
randomaccessfile fromfile = new randomaccessfile ("FromFile.txt", "RW" = Fromfile.getchannel (); Randomaccessfile tofile = new randomaccessfile ("ToFile.txt", "RW" = Tofile.getchannel (); long position = 0; long count = Fromchannel.size (); Tochannel.transferfrom (Fromchannel, position, count);
The parameters position and count, tell where in the destination file to start writing ( position ), and what many bytes to Tran Sfer maximally ( count ). If the source channel count has a fewer than bytes, less is transfered.
Additionally, some implementations may transfer only the data the have ready on its SocketChannel SocketChannel internal buffer here and no W-even If the May later has more SocketChannel data available. Thus, it may not be transfer the entire data requested () from the to count SocketChannel FileChannel .
TransferTo ()
The transferTo() method transfer from a into some and other FileChannel channel. Here are a simple example:
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);
Notice How similar the example was to the previous. The only real difference are the which FileChannel object the method is called on. The rest is the same.
The issue with was SocketChannel also present with the transferTo() method. SocketChannelthe implementation may be transfer bytes from FileChannel the until the send buffer was full, and then stop.
Java NIO (5) channel to channel transfers