Copying file in Java

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.

Copying file with FileInputStream and 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.

CopyFileStream.java
package com.zetcode;

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

public class CopyFileStream {

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

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

        InputStream is = null;
        OutputStream os = null;

        try {
            
            is = new FileInputStream(source);
            os = new FileOutputStream(dest);
            
            byte[] buffer = new byte[1024];
            int length;
            
            while ((length = is.read(buffer)) > 0) {
                
                os.write(buffer, 0, length);
            }
            
        } finally {

            if (is != null) {
                is.close();
            }

            if (os != null) {
                os.close();
            }
        }
    }
}

The example represents the classic Java way of copying files. It copies a file using FileInputStream, FileOutputStream, and File.

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

These are the source and destination files.

is = new FileInputStream(source);
os = new FileOutputStream(dest);

We create instances of FileInputStream and FileOutputStream.

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.

Copying 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.

CopyFileChannel.java
package com.zetcode;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;

public class CopyFileChannel {

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

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

        FileChannel sc = null;
        FileChannel dc = null;
        
        try {
            
            sc = new FileInputStream(source).getChannel();
            dc = new FileOutputStream(dest).getChannel();
            dc.transferFrom(sc, 0, sc.size());
            
        } finally {
            
            if (sc != null) {
                sc.close();
            }

            if (dc != null) {
                dc.close();
            }
        }
    }
}

The example copies a text file with FileChannel.

sc = new FileInputStream(source).getChannel();

The source channel is created from the FileInputStream with the getChannel() method.

dc.transferFrom(sc, 0, sc.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.

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:

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

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 {

        File source = new File("src/resources/bugs.txt");
        File 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.

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.

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

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

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 {
        
        File source = new File("src/main/resources/bugs.txt");
        File dest = new File("src/main/resources/bugs2.txt");        
        
        FileUtils.copyFile(source, dest);
    }
}

The example copies a file with Apache Commons' FileUtils.copyFile().

Copying file with Guava

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

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 {

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

        Files.copy(source, dest);
    }
}

The example copies a file with Guava's Files.copy().

In this tutorial, we have shown several ways how to copy a file in Java. We have used built-in tools and third-party libraries. You might also be interested in the related tutorials: Reading text files in Java, Reading and writing ICO images in Java, Java Swing tutorial, Java tutorial, Displaying image in Java.