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 Libcore.os.read(fd, 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?
Thanks
Solution
I learned a bit about this and came to this conclusion:
4 ways to copy files in Java
- Use apache commons IO to copy files
Copy the file using
java.nio.file.Files.copy().
This method is pretty much fast and simple to write.
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);
inputStream.close();
outputStream.close();
}
- Copy files using FileStreams (if you’re shocked by older Java versions, this one is for you.) )