Java File Copy (easy and fast)FileChannel#transferTo
In JavaCopy FilesThe following is a sample program that does the following
The sample programs are based on the New I/O FileChannel#transferTo method.
This is the simplest coding method, as it allows you to write a program for copy processing without having to be aware of the buffer required for reading data.
What is a channel?
The word channel is used in many different ways.
Basically, it seems to indicate a transmission path for inputting and outputting data between other devices.FileChannel will be a class that represents a connection for reading and writing to a file.
transferTo The method can transfer byte data from the source file to the destination channel.
The following is taken from the JavaAPI documentation.
transferTo(long position, long count, WritableByteChannel target)
Transfers bytes from a file on this channel to the specified writable byte channel.
This method may be much more efficient than a simple loop of reading data from this channel and writing it to the target channel. Many operating systems can transfer bytes directly from the file system cache to the target channel. No bytes are copied at this time.
This verification result shows how to use a normal stream,
The copy process was faster than other FileChannel methods (such as using the ByteBuffer#allocateDirect method).
sample program
FileChannel srcChannel = new
FileInputStream(srcPath).getChannel();
FileChannel destChannel = new
FileOutputStream(destPath).getChannel();
try {
srcChannel.transferTo(0, srcChannel.size(), destChannel);
} finally {
srcChannel.close();
destChannel.close();
}
}
execution (e.g. program)
A 100MB file "100M.txt" is prepared directly under the C drive for file copying of the sample program.
In the sample program C:\100M.txt and copy the C:\a.txt file.
The sample was run in the following environment.
OS : WindowsXP
CPU : Athlon 1.46GHz
Memory : 1GB
JRE : 1.6.4
◆Example of Execution
/** * Execution example * @param args */ public static void main(String[] args) { try { copyTransfer("C:\\100M.txt", "C:\\a.txt"); } } catch (IOException e) { e.printStackTrace(); } } }
FileChannel#transferTo In copy processing using the method
Copying a 100MB file was completed in about 3 seconds. Also, the heap usage during the copy process was about 300 (KB).
By the way,Java file copy (change buffer size)In the method introduced in
When we specified the most efficient buffer size of 1000KB, the processing time was about 4 seconds and the heap usage was about 1,300KB.
Even file copying by stream can be sped up by tuning the buffer size, so
It can be said that there is not much difference in the process of copying a single file.
However, FileChannel can be effective in terms of processing speed and heap usage when large files are copied in succession or when multiple copy operations are performed in parallel.