5

As I found, underlying OS call for the copyToFile() is Libcore.os.read(fd, bytes, byteOffset, byteCount), while transferTo() is based on memory mapped file:

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

Q1: Am I right or wrong in my findings?
Q2: Is there any reason to use FileUtils.copyFile() as FileChannel.transferTo() seems should be more efficient?

Thanks

MobileX
  • 409
  • 4
  • 13

1 Answers1

4

I informed a bit about this and have this conclusion:

4 ways to copy files in java

  1. Copy file using apache commons IO
  2. Copy file using java.nio.file.Files.copy()

    This method is pretty much fast and simple to write.

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

If you are fond of channel classes for their brilliant performance, use this method.

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);

    inputStream.close();
    outputStream.close();
}
  1. Copy file using FileStreams (If you are struck in older java versions, this one is for you.)
Tom11
  • 2,419
  • 8
  • 30
  • 56
PurpleSoft
  • 146
  • 11
  • PurpleSoft, thanks a lot. However, I can't find the Files class in android. Are you sure it exists? – MobileX Feb 02 '16 at 12:20
  • Should be, look at this [link](http://developer.android.com/reference/java/io/File.html) , check your libraries and imports – PurpleSoft Feb 02 '16 at 12:28
  • It's 'File' not 'File**s**'. Also it has no the copy() method. – MobileX Feb 02 '16 at 13:04
  • 2
    Android is Java 6 based, and there is no backport of Java 7's java.nio.file classes to Android. sorry More info: [link](http://developer.android.com/intl/es/reference/java/nio/channels/package-summary.html) – PurpleSoft Feb 02 '16 at 14:55
  • Would have been nice to see example snippets of each case. In addition, in Java 8, case (3) give the following gradle compiler issue: `Resource leak: '' is never closed`. – not2qubit Apr 08 '17 at 09:29