This city is guilty, the crime is life, the sentence is death, darkness descendes!
4 Ways to Copy File in Java
February
25th,
2016
Although Java offers a class that can handle file operations, that is java.io.File, it doesn’t have a copy method that will copy a file to another.
The copying action is an important one, when your program has to handle many file related activities. Nevertheless, there are several ways you can perform a file copying operation in Java and we will discuss four of the most popular in this example.
1.Copy File Using FileStreams
This is the most classic way to copy the content of a file to another. You simply read a number of bytes from File A using FileInputStream and write them to File B using FileOutputStream.
Here is the code of the first method:
As you can see we perform several read and write operations on big chucks of data, so this ought to be a less efficient compared to the next methods we will see.
2.Copy File using java.nio.channels.FileChannel
Java NIO includes a transferFrom method that according to the documentation is supposed to do faster copying operations than FileStreams.
Here is the code of the second method:
3.Copy File using Apache Commons IO
Apache Commons IO offers a copyFile(File srcFile, File destFile) method in its FileUtils class that can be used to copy a file to another. It’s very convenient to work with Apache Commons FileUtils class when you already using it to your project. Basically, this class uses Java NIO FileChannel internally.
Here is the code of the third method:
4.Copy File using Java 7 Files class
If you have some experience in Java 7 you will probably know that you can use the copy mehtod of the class Files in order to copy a file to another.
Here is the code of the fourth method:
Test
Now to see which one of these methods is more efficient we will copy a large file using each one of them in a simple program. To avoid any performance speedups from caching we are going to use four different source files and four different destination files.
Let’s take a look at the code:
Output:
As you can see FileChannels is the best way to copy large files. If you work with even larger files you will notice a much bigger speed difference.
This was an example that demonstrates four different ways you can copy a File in Java.