Java NIO (5) channel to channel transfers

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.