Copying a file using Channel

suggest change

We can use a FileChannel to copy a file's contents. FileChannel.transferTo() asks the operating system to transfer bytes from this channel to another.

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

public class FileCopier {
    
    public static void main(String[] args) {
        File sourceFile = new File("hello.txt");
        File sinkFile = new File("hello2.txt");
        copy(sourceFile, sinkFile);
    }

    public static void copy(File sourceFile, File destFile) {
        if (!sourceFile.exists()) {
            System.out.println("Source file doesn't exist");
            return;
        }

        // FileOutputStream creates destFile if it does not exist.
        try (FileChannel srcChannel = new FileInputStream(sourceFile).getChannel();
             FileChannel sinkChannel = new FileOutputStream(destFile).getChannel()) {

            // A single transferTo call can copy fewer bytes than requested.
            long position = 0;
            long size = srcChannel.size();
            while (position < size) {
                position += srcChannel.transferTo(position, size - position, sinkChannel);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents