Java – FileUtils.copyFile() VS FileChannel.transferTo()

FileUtils.copyFile() VS FileChannel.transferTo()… here is a solution to the problem.

FileUtils.copyFile() VS FileChannel.transferTo()

I found that the underlying OS call for copyToFile() is, bytes, byteOffset, byteCount), while transferTo() is based on a memory-mapped file:

MemoryBlock.mmap(fd, alignment, size + offset, mapMode);
buffer = map(MapMode.READ_ONLY, position, count);
return target.write(buffer);

Q1: Is my finding right or wrong?
Q2: Is there any reason to use FileUtils.copyFile() because FileChannel.transferTo() seems supposed to be more efficient?



I learned a bit about this and came to this conclusion:

4 ways to copy files in Java

  1. Use apache commons IO to copy files
  2. Copy the file using java.nio.file.Files.copy().

    This method is pretty much fast and simple to write.

  3. Copy the file using java.nio.channels.FileChannel.transferTo().

Use this method if you like the excellent performance of the Channel class.

private static void fileCopyUsingNIOChannelClass() throws IOException 
    File fileToCopy = new File("c:/temp/testoriginal.txt");
    FileInputStream inputStream = new FileInputStream(fileToCopy);
    FileChannel inChannel = inputStream.getChannel();

File newFile = new File("c:/temp/testcopied.txt");
    FileOutputStream outputStream = new FileOutputStream(newFile);
    FileChannel outChannel = outputStream.getChannel();

inChannel.transferTo(0, fileToCopy.length(), outChannel);

  1. Copy files using FileStreams (if you’re shocked by older Java versions, this one is for you.) )

Related Problems and Solutions