Java - Copying Contents with File Channels

Introduction

You can use buffers and channels to copy a file.

Get the FileChannel object for the source file and the destination file, and call the transferTo() method on the source FileChannel object or call the transferFrom() method on the sink FileChannel object.

The following code shows how to copy file Main.java to test_copy.txt:

// Obtain the source and sink channels
FileChannel sourceChannel = new FileInputStream(sourceFile).getChannel();
FileChannel sinkChannel = new FileOutputStream(sinkFile).getChannel();

// Copy source file contents to the sink file
sourceChannel.transferTo(0, sourceChannel.size(), sinkChannel);

Instead of using the transferTo() method on the source channel, you can also use the transferFrom() method on the sink channel

sinkChannel.transferFrom(sourceChannel, 0, sourceChannel.size());

The following code contains the complete code for copying files.

Demo

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

public class Main {
  public static void main(String[] args) {
    File sourceFile = new File("Main.java");
    File sinkFile = new File("test_copy.txt");
    try {/*from  w w  w . j a v  a2s .c  o  m*/
      copy(sourceFile, sinkFile, false);
      System.out.println(sourceFile.getAbsoluteFile() + " has been copied to "
          + sinkFile.getAbsolutePath());
    } catch (IOException e) {
      System.out.println(e.getMessage());
    }
  }

  public static void copy(File sourceFile, File sinkFile, boolean overwrite)
      throws IOException {

    String msg = "";

    // Perform some error checks
    if (!sourceFile.exists()) {
      msg = "Source file " + sourceFile.getAbsolutePath() + " does not exist.";
      throw new IOException(msg);
    }

    if (sinkFile.exists() && !overwrite) {
      msg = "Destination file " + sinkFile.getAbsolutePath()
          + " already exists.";
      throw new IOException(msg);
    }

    // Obtain source and sink file channels in a
    // try-with-resources block, so they are closed automatically.
    try (FileChannel srcChannel = new FileInputStream(sourceFile).getChannel();
        FileChannel sinkChannel = new FileOutputStream(sinkFile).getChannel()) {

      // Copy source file contents to the sink file
      srcChannel.transferTo(0, srcChannel.size(), sinkChannel);
    }
  }
}

Result

Related Topic