Java Copy File with Files.copy() API

In this example, I show you how to copy a file in Java using Files.copy() API.

java.nio.file.Files.copy() API

This method copy a file to a target file.
This method copies a file to the target file with the options parameter specifying how the copy is performed. By default, the copy fails if the target file already exists or is a symbolic link, except if the source and target are the same file, in which case the method completes without copying the file.

Java Files.copy() API Example

Let's first create a file named "sample1.txt" and enter some text in it. Once you run below program, the content of  "sample1.txt" file should be copied to "sample2.txt" file:
package net.javaguides.corejava.io;

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

public class JavaCopyFile {

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

        File source = new File("src/sample1.txt");
        File dest = new File("src/sample2.txt");

        Files.copy(source.toPath(), dest.toPath(),
            StandardCopyOption.REPLACE_EXISTING);
    }
}
Output:
File created
In the example, we copy a file.
Observe the below code snippet, the Files.copy() takes the following parameters: the path to the source file, the path to the destination file, and the copy options. StandardCopyOption.REPLACE_EXISTING causes the destination file to be replaced if it already exists.
Files.copy(source.toPath(), dest.toPath(), StandardCopyOption.REPLACE_EXISTING);


Comments