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.

FileCopyUsingFileChannel.java

package tips.nio.copyusingfc;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.channels.FileChannel;

public class FileCopyUsingFileChannel {

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

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

        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 Output.java. It is to this Output.java 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.

Comments

comments

About Krishna Srinivasan

He is Founder and Chief Editor of JavaBeat. He has more than 8+ years of experience on developing Web applications. He writes about Spring, DOJO, JSF, Hibernate and many other emerging technologies in this blog.

Speak Your Mind

*