Java IO - Copy a file

November 26, 2019 No comments Java IO Copy File

1. Introduction

This article presents common ways to copy a file in Java. In this tutorial, we will use the built-in methods available in Java IO and the newest NIO API. We will also showcase two third-party libraries like Guava and Commons-IO.

2. Copy file using FileStreams

To copy a file from one location to another we can use Java FileStreams. FileInputStream for reading the file and FileOutputStream for writing the content. FileStreams are available in the Java IO API.

In the following example, we use streams to create an exact copy of the file located under /tmp/frontbackend.txt path. The output file will be placed in /tmp/frontbackend.copy.txt.

package com.frontbackend.java.io.copy;

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

public class CopyFileUsingFileStreams {

    public static void main(String[] args) throws IOException {
        File fileToCopy = new File("/tmp/frontbackend.txt");
        FileInputStream input = new FileInputStream(fileToCopy);

        File newFile = new File("/tmp/frontbackend.copy.txt");
        FileOutputStream output = new FileOutputStream(newFile);

        byte[] buf = new byte[1024];
        int bytesRead;

        while ((bytesRead = input.read(buf)) > 0) {
            output.write(buf, 0, bytesRead);
        }

        input.close();
        output.close();
    }
}

As you can see a lot of happening here. We created an instance of FileInputStream and FileOutputStream, one to read and one to write the content. Copying will use chunks of 1024 bytes for better performance. input.read() the method reads bytes from the original file to the buffer and output.write() method write bytes from buffer to the output file.

3. Copy file using Files.copy()

The good news is Java improved its IO API and from version 7 we can copy a file easier and almost in a single line of code using. The new API provides a java.nio.file.Files class with copy(Path, Path, CopyOption...) method that takes three parameters:

  • the path to the source file (source),
  • path to target file (target),
  • optional third parameter with copy options (options).

The options parameter may include any of the following:

  • REPLACE_EXISTING - if the target file exists it will be replaced,
  • COPY_ATTRIBUTES - to copy all file attributes associated with the source file to target file,
  • NOFOLLOW_LINKS - this parameter indicates that symbolic links should not be followed.

The following example copies a file with Files.copy() method and replaces the target file if it already exists (so we will be using REPLACE_EXISTING in this case):

package com.frontbackend.java.io.copy;

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

public class CopyFileUsingFilesCopy {

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

        File source = new File("/tmp/frontbackend.txt");
        File dest = new File("/tmp/frontbackend.copy.txt");

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

4. Copy file using FileChannel

FileChannel provides a channel for reading, writing, mapping, and manipulating. We can use it to transfer content from one file into another.

The following code example shows you how to copy file contents using the File Channel class:

package com.frontbackend.java.io.copy;

import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.channels.FileChannel;

public class CopyFileUsingFileChannel {

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

        RandomAccessFile source = new RandomAccessFile("/tmp/frontbackend.txt", "r");
        RandomAccessFile dest = new RandomAccessFile("/tmp/frontbackend.copy.txt", "rw");

        FileChannel sfc = source.getChannel();
        FileChannel dfc = dest.getChannel();

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

In this example we use RandomAccessFile object to open file in read new RandomAccessFile("/tmp/frontbackend.txt", "r") and write mode new RandomAccessFile("/tmp/frontbackend.copy.txt", "rw").

The FileChannel.transferFrom() method transfers all bytes from the source channel into the target channel.

The method takes three parameters:

  • the first parameter is the source channel,
  • the second parameter is the starting position of the transfer,
  • the third parameter is the maximum number of bytes that should be transferred.

5. Copy file using Apache Commons IO

To copy a file from one location to another we can also use third-party libraries. commons-io is one of that library that provides a simple method to copy file content from source to the target.

To use Apache Commons IO library we need to include commons-io artifact to our project:

<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.6</version>
</dependency>

The following example shows how to copy a file using commons-io library:

package com.frontbackend.java.io.copy;

import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.IOException;

public class CopyFileUsingCommonIO {

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

        File source = new File("/tmp/frontbackend.txt");
        File dest = new File("/tmp/frontbackend.copy.txt");

        FileUtils.copyFile(source, dest);
    }
}

We used FileUtils.copyFile() a method that takes source and destination files as parameters. Copy operation happens under the hood.

6. Copy file using Guava

Google Guava is an open-source library that supports common operations in an elegant way. To start working with this library we need to include the dependency in our pom.xml file (in case we use maven).

In pom.xml this dependency will look like the following:

<dependency>
    <groupId>com.google.guava</groupId>
    <artifactId>guava</artifactId>
    <version>23.0</version>
</dependency>

The following snippet shows how to copy a file using Guava library:

package com.frontbackend.java.io.copy;

import com.google.common.io.Files;

import java.io.File;
import java.io.IOException;

public class CopyFileUsingGuava {

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

        File source = new File("/tmp/frontbackend.txt");
        File dest = new File("/tmp/frontbackend.copy.txt");

        Files.copy(source, dest);
    }
}

We use Files.copy() a method that takes source and destination file as a parameter.

7. Conclusion

In this tutorial, we presented ways to copy a file from one location to another using inner Java classes from old IO and newest NIO API. We have external libraries that provide one line methods to copy files and hides all the complex login under the hood. It is up to you and your system requirements which method you will choose.

As usual, the snippet codes from this tutorial will be available in our GitHub repository.

{{ message }}

{{ 'Comments are closed.' | trans }}