Reputation: 419
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
Upvotes: 5
Views: 3815
Reputation: 154
I studied a bit about this and have this conclusion:
3 ways to copy files in java
Copy file using java.nio.file.Files.copy()
This method is pretty much fast and simple to write.
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();
}
FileStreams
(If you are stuck in older java versions, this one is for you.)Upvotes: 4