FileFileChannelFileInputStreamFileOutputStream

4 Ways to Copy File in Java

Photo of Ilias TsagklisIlias TsagklisFebruary 19th, 2013Last Updated: November 9th, 2023
2 831 3 minutes read

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 usingFileInputStream and write them to File B usingFileOutputStream.

Here is the code of the first method:

 private static void copyFileUsingFileStreams(File source, File dest)throws IOException {InputStream input = null;OutputStream output = null;try {input = new FileInputStream(source);output = new FileOutputStream(dest);byte[] buf = new byte[1024];int bytesRead;while ((bytesRead = input.read(buf)) > 0) {output.write(buf, 0, bytesRead);}} finally {input.close();output.close();}}

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 usingjava.nio.channels.FileChannel

Java NIO includes atransferFrom method that according to the documentation is supposed to do faster copying operations than FileStreams.

Here is the code of the second method:

private static void copyFileUsingFileChannels(File source, File dest)throws IOException {FileChannel inputChannel = null;FileChannel outputChannel = null;try {inputChannel = new FileInputStream(source).getChannel();outputChannel = new FileOutputStream(dest).getChannel();outputChannel.transferFrom(inputChannel, 0, inputChannel.size());} finally {inputChannel.close();outputChannel.close();}}

3. Copy File using Apache Commons IO

Apache Commons IO offers acopyFile(File srcFile, File destFile) method in itsFileUtils class that can be used to copy a file to another. It’s very convenient to work with Apache CommonsFileUtils class when you already using it to your project. Basically, this class uses Java NIOFileChannel internally.

Here is the code of the third method:

private static void copyFileUsingApacheCommonsIO(File source, File dest)throws IOException {FileUtils.copyFile(source, dest);}

4. Copy File using Java 7Files class

If you have some experience in Java 7 you will probably know that you can use thecopy mehtod of the classFiles in order to copy a file to another.

Here is the code of the fourth method:

private static void copyFileUsingJava7Files(File source, File dest)throws IOException {Files.copy(source.toPath(), dest.toPath());}

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:

package com.javacodegeeks.java.core;import java.io.File;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import java.nio.channels.FileChannel;import java.nio.file.Files;import org.apache.commons.io.FileUtils;public class CopyFilesExample {public static void main(String[] args) throws InterruptedException,IOException {File source = new File("C:\\Users\\nikos7\\Desktop\\files\\sourcefile1.txt");File dest = new File("C:\\Users\\nikos7\\Desktop\\files\\destfile1.txt");// copy file using FileStreamslong start = System.nanoTime();long end;copyFileUsingFileStreams(source, dest);System.out.println("Time taken by FileStreams Copy = "+ (System.nanoTime() - start));// copy files using java.nio.FileChannelsource = new File("C:\\Users\\nikos7\\Desktop\\files\\sourcefile2.txt");dest = new File("C:\\Users\\nikos7\\Desktop\\files\\destfile2.txt");start = System.nanoTime();copyFileUsingFileChannels(source, dest);end = System.nanoTime();System.out.println("Time taken by FileChannels Copy = " + (end - start));// copy file using Java 7 Files classsource = new File("C:\\Users\\nikos7\\Desktop\\files\\sourcefile3.txt");dest = new File("C:\\Users\\nikos7\\Desktop\\files\\destfile3.txt");start = System.nanoTime();copyFileUsingJava7Files(source, dest);end = System.nanoTime();System.out.println("Time taken by Java7 Files Copy = " + (end - start));// copy files using apache commons iosource = new File("C:\\Users\\nikos7\\Desktop\\files\\sourcefile4.txt");dest = new File("C:\\Users\\nikos7\\Desktop\\files\\destfile4.txt");start = System.nanoTime();copyFileUsingApacheCommonsIO(source, dest);end = System.nanoTime();System.out.println("Time taken by Apache Commons IO Copy = "+ (end - start));}private static void copyFileUsingFileStreams(File source, File dest)throws IOException {InputStream input = null;OutputStream output = null;try {input = new FileInputStream(source);output = new FileOutputStream(dest);byte[] buf = new byte[1024];int bytesRead;while ((bytesRead = input.read(buf)) > 0) {output.write(buf, 0, bytesRead);}} finally {input.close();output.close();}}private static void copyFileUsingFileChannels(File source, File dest)throws IOException {FileChannel inputChannel = null;FileChannel outputChannel = null;try {inputChannel = new FileInputStream(source).getChannel();outputChannel = new FileOutputStream(dest).getChannel();outputChannel.transferFrom(inputChannel, 0, inputChannel.size());} finally {inputChannel.close();outputChannel.close();}}private static void copyFileUsingJava7Files(File source, File dest)throws IOException {Files.copy(source.toPath(), dest.toPath());}private static void copyFileUsingApacheCommonsIO(File source, File dest)throws IOException {FileUtils.copyFile(source, dest);}}

Output:

Time taken by FileStreams Copy = 127572360Time taken by FileChannels Copy = 10449963Time taken by Java7 Files Copy = 10808333Time taken by Apache Commons IO Copy = 17971677

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.

Do you want to know how to develop your skillset to become aJava Rockstar?
Subscribe to our newsletter to start Rockingright now!
To get you started we give you our best selling eBooks forFREE!
1. JPA Mini Book
2. JVM Troubleshooting Guide
3. JUnit Tutorial for Unit Testing
4. Java Annotations Tutorial
5. Java Interview Questions
6. Spring Interview Questions
7. Android UI Design
and many more ....
I agree to theTerms andPrivacy Policy

Thank you!

We will contact you soon.

Photo of Ilias TsagklisIlias TsagklisFebruary 19th, 2013Last Updated: November 9th, 2023
2 831 3 minutes read
Photo of Ilias Tsagklis

Ilias Tsagklis

Ilias is a software developer turned online entrepreneur. He is co-founder and Executive Editor atJava Code Geeks.
Subscribe
Notify of
guest
I agree to theTerms andPrivacy Policy
The comment form collects your name, email and content to allow us keep track of the comments placed on the website. Please read and accept our website Terms and Privacy Policy to post a comment.

I agree to theTerms andPrivacy Policy
The comment form collects your name, email and content to allow us keep track of the comments placed on the website. Please read and accept our website Terms and Privacy Policy to post a comment.