Java Copy File - 4 Ways to Copy File in Java With Examples

Java copy file is a very common operation. But class doesn’t have any shortcut method to copy a file from source to destination. Here we will learn about four different ways we can copy file in java.

Java Copy File

  1. Java Copy File – Stream

This is the conventional way of file copy in java. Here we create two Files – source and destination. Then we create InputStream from source and write it to the destination file using OutputStream for java copy file operation.

Here is the method that can be used for java copy file using streams.

  1. Java Copy File – java.nio.channels.FileChannel

Java NIO classes were introduced in Java 1.4 and FileChannel can be used to copy file in java. According to transferFrom() method javadoc, this way of copy file is supposed to be faster than using Streams for java copy files.

Here is the method that can be used to copy a file using FileChannel.

  1. Java Copy File – Apache Commons IO FileUtils

Apache Commons IO FileUtils.copyFile(File srcFile, File destFile) can be used to copy file in java. If you are already using Apache Commons IO in your project, it makes sense to use this for code simplicity. Internally it uses Java NIO FileChannel, so you can avoid this wrapper method if you are not already using it for other functions.

Here is the method for using apache commons io for java copy file operation.

  1. Java Copy File – Files class

If you are working on Java 7 or higher, you can use Files class copy() method to copy file in java. It uses File System providers to copy the files.

Now to find out which is the fastest method, I wrote a test class and executed above methods one-by-one for copy file of 1 GB. In each call, I used different files to avoid any benefit to later methods because of caching.

Here is the output of the above program, note that I commented above code to make sure every time only one method is used for java file copy operation.

From the output, it’s clear that Stream Copy is the best way to copy File in Java. But it’s a very basic test. If you are working on a performance intensive project, then you should try out different methods for java copy file and note down the timings to figure out the best approach for your project.

You should also play around different ways of java copy files based on your average size of the file.

I have created a YouTube video for 4 ways to copy the file in java, you can watch it to learn more.

By admin

Leave a Reply

%d bloggers like this: