Java copy file – learn how to copy a file in Java

Copying file in Java

last modified October 22, 2022

In Java copy file tutorial, we show how to copy a file in Java. We copy files
with built-in classes including File, FileInputStream,
FileOutputStream, FileChannel, and Files.
We also use two third-party libraries: Apache Commons IO and Google Guava.

File copying is the creation of a new file which has the same content
as an existing file. File moving is transferring a file from one
location to another.

The file to be copied is called the source file and the new copy is called the
destination file.

The Bugs file

In the example, we use a bugs.txt file.

bugs.txt

Assasin bug, Avondale spider, Backswimmer,
Bamboo moth, Banana moth, Bed bug,
Black cocroach, Blue moon, Bumble Bee,
Carpenter Bee, Cattle tick, Cave Weta,
Cicada, Cinnibar, Click beetle, Clothes moth,
Codling moth, Centipede, Earwig, Eucalypt longhorn beetle,
Field Grasshopper, Garden slug, Garden soldier,
German cockroach, German wasp, Giant dragonfly,
Giraffe weevil, Grass grub, Grass looper,
Green planthopper, Green house spider, Gum emperor,
Gum leaf skeletoniser, Hornet, Mealybug,
Mites, Mole Cricket, Monarch butterfly,
Mosquito, Silverfish, Wasp,
Water boatman, Winged weta, Wolf spider,
Yellow Jacket, Yellow Admiral

This is a simple file containing names of bugs.

Java copy file with FileInputStream & FileOutputStream

With FileInputStream and FileOutputStream we
create streams for reading and writing to a File. When
the file is not found, FileNotFoundException is thrown.
File is a representation of a file or directory in Java.

com/zetcode/CopyFileStream.java

package com.zetcode;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class CopyFileStream {

    public static void main(String[] args) throws IOException {

        var source = new File("src/resources/bugs.txt");
        var dest = new File("src/resources/bugs2.txt");

        try (var fis = new FileInputStream(source);
             var fos = new FileOutputStream(dest)) {

            byte[] buffer = new byte[1024];
            int length;

            while ((length = fis.read(buffer)) > 0) {

                fos.write(buffer, 0, length);
            }
        }
    }
}

The example copies a file using FileInputStream, FileOutputStream,
and File.

try (var fis = new FileInputStream(source);
     var fos = new FileOutputStream(dest)) {

We create instances of FileInputStream and
FileOutputStream. The try-with-resources statement will
automatically close the streams.

byte[] buffer = new byte[1024];

We will be copying chunks of 1024 bytes of text. This is done for better
performance.

while ((length = is.read(buffer)) > 0) {

The FileInputStream's read method reads the specified
number of bytes from the input stream and stores them into the buffer array. It
returns the total number of bytes read into the buffer, or -1 if there is no
more data because the end of the stream has been reached.

os.write(buffer, 0, length);

The FileOutputStream's write method writes the bytes
stored in the buffer to the output stream. The first parameter is the data, the
second is the start offset in the data, and the last is the number of bytes to
write.

Java copy file with Paths & Files

The next example is similar to the previous one; it uses
more modern API.

com/zetcode/CopyFileStream2.java

package com.zetcode;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;

public class CopyFileStream2 {

    public static void main(String[] args) throws IOException {

        var source = Paths.get("src/resources/bugs.txt");
        var dest = Paths.get("src/resources/bugs2.txt");

        try (var fis = Files.newInputStream(source);
             var fos = Files.newOutputStream(dest)) {

            byte[] buffer = new byte[1024];
            int length;

            while ((length = fis.read(buffer)) > 0) {

                fos.write(buffer, 0, length);
            }
        }
    }
}

We copy the file using Paths and Files classes.

var source = Paths.get("src/resources/bugs.txt");
var dest = Paths.get("src/resources/bugs2.txt");

From the files we create Path objects.

try (var fis = Files.newInputStream(source);
     var fos = Files.newOutputStream(dest)) {

The streams are created with the help of the Files class.

Java copy file with FileChannel

FileChannel is a channel for reading, writing, mapping, and
manipulating a file. FileChannel is an alternative way to the
classic Java IO stream API. It is located in the java.nio package.

RandomAccessFile supports both reading and writing to a random
access file. A random acces means that we can read or write information anywhere
in the file.

com/zetcode/CopyFileChannel.java

package com.zetcode;

import java.io.IOException;
import java.io.RandomAccessFile;

public class CopyFileChannel {
    
    public static void main(String[] args) throws IOException {

        var source = new RandomAccessFile("src/resources/bugs.txt", "r");
        var dest = new RandomAccessFile("src/resources/bugs2.txt", "rw");

        try (var sfc = source.getChannel();
             var dfc = dest.getChannel()) {

            dfc.transferFrom(sfc, 0, sfc.size());
        }
    }
}

The example copies a text file with FileChannel.

var source = new RandomAccessFile("src/resources/bugs.txt", "r");

A random access file in a read mode is created.

var dest = new RandomAccessFile("src/resources/bugs2.txt", "rw");

A random access file in a read/write mode is created.

try (var sfc = source.getChannel();
    var dfc = dest.getChannel()) {

We get channels from the files with getChannel.

dfc.transferFrom(sfc, 0, sfc.size());

The transferFrom method transfers bytes from the source channel
into the destination channel. The first parameter is the source channel, the
second is the starting position of the transfer in the file, and the third is
the maximum number of bytes to be transferred.

Java copying file with Files.copy

Java 7 introduced the Files.copy method, which provides an easy way
of copying a file. The copy fails if the target file exists, unless the
REPLACE_EXISTING option is specified. Files.copy
takes an optional third copy options argument.

The options parameter may include any of the following:

  • REPLACE_EXISTING – if the target file exists, then the target file is replaced
    if it is not a non-empty directory.
  • COPY_ATTRIBUTES – attempts to copy the file attributes associated with this file to the target file.
  • ATOMIC_MOVE – moves the file.
  • NOFOLLOW_LINKS – symbolic links are not followed.

The first three options are available in StandarCopyOption; the
last one in LinkOption.

com/zetcode/CopyFileJava7.java

package com.zetcode;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;

public class CopyFileJava7 {

    public static void main(String[] args) throws IOException {

        var source = new File("src/resources/bugs.txt");
        var dest = new File("src/resources/bugs2.txt");

        Files.copy(source.toPath(), dest.toPath(),
                StandardCopyOption.REPLACE_EXISTING);
    }
}

The example copies a file with Files.copy. It replaces the
destination if it already exists.

Java Copying file with Apache Commons IO

Apache Commons IO is a library of utilities to assist with developing IO
functionality. It contains the FileUtils.copyFile method to perform
copying.

FileUtils.copyFile copies the contents of the specified source file
to the specified destination file preserving the file date. The directory
holding the destination file is created if it does not exist. If the destination
file exists, then this method will overwrite it.

implementation 'commons-io:commons-io:2.11.0'

For this example, we need the commons-io artifact.

com/zetcode/CopyFileApacheCommons.java

package com.zetcode;

import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;

public class CopyFileApacheCommons {

    public static void main(String[] args) throws IOException {

        var source = new File("src/main/resources/bugs.txt");
        var dest = new File("src/main/resources/bugs2.txt");

        FileUtils.copyFile(source, dest);
    }
}

The example copies a file with Apache Commons’ FileUtils.copyFile.

Java copying file with Guava

Google Guava is an open-source set of common libraries for Java. It includes
Files.copy for copying a file.

implementation 'com.google.guava:guava:31.1-jre'

We use Guava dependency.

com/zetcode/CopyFileGuava.java

package com.zetcode;

import com.google.common.io.Files;
import java.io.File;
import java.io.IOException;

public class CopyFileGuava {

    public static void main(String[] args) throws IOException {

        var source = new File("src/main/resources/bugs.txt");
        var dest = new File("src/main/resources/bugs2.txt");

        Files.copy(source, dest);
    }
}

The example copies a file with Guava’s Files.copy.

In this article, we have shown several ways how to copy a file in Java. We have
used built-in tools and third-party libraries.

List all Java tutorials.