There is several ways to copy file from one location to another. 4 ways will be shown here :

  1. Writing a InputStream to an OutputStream
  2. Using FileChannel
  3. Using java.nio.file.Files
  4. Using Apache Commons IO FileUtils

1- Writing a InputStream to an OutputStream

JDK 1.0+

First step to copy files is by using basic Java code by reading a InputStream (source file) and writing it to a OuputStream that corresponds to your destination file. Below an example :

Note that i used Try with resources. Files are closed automatically.

2- Using fileChannel

JDK 1.4+

You can use the transferFrom or transfertTo methods of FileChannel to make the copy. Below how to do :

3- Using java.nio.file.Files

JDK 1.7+

Since Java 1.7, the static class java.nio.file.Files is given to operate on files and directories. It provides the method Copy to copy files. Below of to use it :

4- Using Apache Commons IO FileUtils

Since JDK 1.6 For Commons IO 2.4

Since JDK 1.5 For Commons IO 2.2

Appache Commons IO provides FileUtils to handle files and folders. It can be useful to copy files.

  • Download the dependency

If you are working on a Maven project, add the following to your pom.xml

If not, download the jar and add it to your classpath.

  • Copy files