Java File Copy Example

In this source code example, we show you how to copy a file in Java.

Java 7 introduced java.nio.file.Files class that consists exclusively of static methods that operate on files, directories, or other types of files.

We use Files.copy() method to copy all bytes from an input stream to a file.

Java File Copy Example

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 {

        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);
    }
}
Note that we are using Files.copy() method to copy a file from the source location to the destination location.

References

Related Java NIO Files Examples


Comments