FileUtils.copyFile() VS FileChannel.transferTo()

Mob*_*leX 5 java android filechannel file-copying fileutils

正如我发现的,底层操作系统调用 is copyToFile()Libcore.os.read(fd, bytes, byteOffset, byteCount)whiletransferTo()基于内存映射文件:

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

Q1:我的发现是对还是错?
Q2:有什么理由使用FileUtils.copyFile()asFileChannel.transferTo()似乎应该更有效吗?

谢谢

Pur*_*oft 4

我对此进行了一些了解并得出以下结论:

java中复制文件的4种方法

  1. 使用 apache commons IO 复制文件
  2. 使用复制文件java.nio.file.Files.copy()

    这种方法非常快速且易于编写。

  3. 使用复制文件java.nio.channels.FileChannel.transferTo()

如果您喜欢通道类的出色性能,请使用此方法。

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();
}
Run Code Online (Sandbox Code Playgroud)
  1. 使用 FileStreams 复制文件(如果您对旧的 java 版本感到震惊,那么这个版本适合您。)

  • Android 基于 Java 6,并且 Java 7 的 java.nio.file 类没有向后移植到 Android。抱歉更多信息:[链接](http://developer.android.com/intl/es/reference/java/nio/channels/package-summary.html) (2认同)