How do I copy file using FileChannel class?

The example below show you how to copy a file using the java.nio.channels.FileChannel class.


import java.nio.channels.FileChannel;

public class FileCopy {
    public static void main(String[] args) {
        //// Define the source and target file
        File source = new File("D:/Temp/source.txt");
        File target = new File("D:/Temp/target.txt");

        // Create the source and target channel
        try (FileChannel sourceChannel = new FileInputStream(source).getChannel();
             FileChannel targetChannel = new FileOutputStream(target).getChannel()) {

            // Copy data from the source channel into the target channel
            targetChannel.transferFrom(sourceChannel, 0, sourceChannel.size());
        } catch (Exception e) {


  1. Hello my friend.

    When I do it like your example it show to me that my path is not correct. When I check this error I found something about folder bin where Java JDK install. How can I resolve that?



Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.