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
- Java File Copy Example
- Java Create File Example
- Java Delete File Example
- Java File Size Example
- Java Get File Owner Example
- Java File Move Example
- Java Read File Example
- Java Write File Example
- Java Create Directory Example
- Java Create Multiple Directories Example
- Java List All Subdirectories From a Directory Example
- Java Append to File Example
Free Spring Boot Tutorial - 5 Hours Full Course
Watch this course on YouTube at Spring Boot Tutorial | Fee 5 Hours Full Course