Home » Data Transfer between Channels

Data Transfer between Channels

by Online Tutorials Library

Data Transfer between Channels

In Java NIO we can directly transfer the data from one channel to another very frequently. The transfer of file data in bulk is very common that a couple of optimization methods have been added to FileChannel class for making it more efficient.

The two methods added to FileChannel class for data transfer between channels are:

  1. FileChannel.transferTo() method
  2. FileChannel.transferFrom() method

FileChannel.transferTo() method

The transferTo() method allows the data transfer from a FileChannel into some other channel.

Let’s see the example of transferTo() method:


FileChannel.transferFrom() method

The transferFrom() method allows the data transfer from a source channel into the FileChannel.

Let’s see the example of transferFrom() method:


Basic Channel to Channel Data Transfer Example

Let’s see the simple example of reading the file contents from 4 different files and write their combined output into a fifth file:

Output:

In above program the content of 4 different files i.e. input1.txt, input2.txt, input3.txt and input4.txt is read and write their combined output into a fifth file i.e. combine_output.txt.

Next TopicJava NIO Selector

You may also like