Copying File Contents using FileChannel

In this technical tip, let us see an easy way of achieving file copy using File Channels. File Channels are part of Java New I/O Packages. A file can be viewed as a sequence of bytes. The various Buffer classes in New I/O Packages serve as a container for manipulating the primitive byte contents. It is also possible to allocate a new Buffer object, read and write byte data into the existing Buffer using the Buffer classes. The File Channel objects are tightly associated with the Buffer class, and now File objects are coupled with File Channel object which means that it is now possible to perform read and write data on the files using the File Channel objects.

also read:

The following code snippet will show you how to copy file contents using the File Channel class.

package tips.nio.copyusingfc;

import java.nio.channels.FileChannel;

public class FileCopyUsingFileChannel {

    public static void main(String[] args) throws Exception{

        String thisFile = "./src/tips/nio/copyusingfc/";
        FileInputStream source = new FileInputStream(thisFile);
        FileOutputStream destination = new FileOutputStream("");

        FileChannel sourceFileChannel = source.getChannel();
        FileChannel destinationFileChannel = destination.getChannel();

        long size = sourceFileChannel.size();
        sourceFileChannel.transferTo(0, size, destinationFileChannel);

In the above program, we have created an input stream and an output stream object. The input stream points to the current java file and the output stream is pointing to It is to this we want the contents of the file to be transferred. As mentioned earlier, a file object is associated with a File Channel object. So, we obtain the File Channel object for both the input and the output stream using the following code,

FileChannel sourceFileChannel = source.getChannel();
FileChannel destinationFileChannel = destination.getChannel();

To make the copy operation to happen, we call the FileChannel.transferTo() method on the source file object passing the starting position, the number of bytes to be transferred and the target channel object.

Leave a Reply

Your email address will not be published. Required fields are marked *

Pin It on Pinterest

Share This

Share this post with your friends!