Copying a file is a very common operation. But Java does not come with a ready make file copy function in the java.io.File class.

We will explore couple of common ways in which files can be copied in Java

1. Using Streams

This is the most conventional way of copying files in Java. Convert the file into a bytes stream with FileInputStream and write the bytes into another file with FileOutputStream.


private static void copyFile(File source, File destination) throws IOException {
    InputStream is = null;
    OutputStream os = null;
    try {
        is = new FileInputStream(source);
        os = new FileOutputStream(destination);
        byte[] buffer = new byte[1024]; //buffer size
        int length;
        while ((length = is.read(buffer)) > 0) {
            os.write(buffer, 0, length);
        }
    } finally {
        is.close();
        os.close();
    }
}

2. Using 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.


private static void copyFile(File source, File destination) throws IOException {
    FileChannel sourceChannel = null;
    FileChannel destChannel = null;
    try {
        sourceChannel = new FileInputStream(source).getChannel();
        destChannel = new FileOutputStream(destination).getChannel();
        destChannel.transferFrom(sourceChannel, 0, sourceChannel.size());
       }finally{
           sourceChannel.close();
           destChannel.close();
   }
}

3. Using 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.


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

4. Using 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.


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