Java Files copy()

In this guide, you will learn about the Files.copy() method in Java programming and how to use it with an example.

1. Files copy() Method Overview

Definition:

The Files.copy() method in Java's NIO (New I/O) package is used to copy files or directories. It offers various overloaded methods to define the source and target of the copy operation, as well as the manner in which the copy should be conducted.

Syntax:

1) static long copy(Path source, OutputStream out) throws IOException 
2) static Path copy(Path source, Path target, CopyOption... options) throws IOException

Parameters:

- source: the path to the file to copy.

- target: the path to the target file.

- out: the output stream to which the file bytes will be copied.

- options: optional arguments that specify how the copy should be done. Common options include REPLACE_EXISTING and COPY_ATTRIBUTES.

Key Points:

- The method throws an IOException if an I/O error occurs or the source and target parameters are the same.

- The REPLACE_EXISTING option can be used to replace an existing file.

- The COPY_ATTRIBUTES option can be used to copy all file attributes, including timestamps.

- The method can be used for both regular files and directories.

2. Files copy() Method Example


import java.io.IOException;
import java.nio.file.CopyOption;
import java.nio.file.FileAlreadyExistsException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;

public class FilesCopyExample {
    public static void main(String[] args) {
        Path sourcePath = Paths.get("source.txt");
        Path targetPath = Paths.get("target.txt");

        try {
            Files.copy(sourcePath, targetPath, StandardCopyOption.REPLACE_EXISTING);
            System.out.println("File copied successfully!");
        } catch (FileAlreadyExistsException e) {
            System.out.println("Target file already exists. Use REPLACE_EXISTING option to overwrite it.");
        } catch (IOException e) {
            System.out.println("An I/O error occurred: " + e.getMessage());
        }
    }
}

Output:

File copied successfully!

Explanation:

In the example, we attempt to copy a file named source.txt to a file named target.txt

We use the REPLACE_EXISTING option to replace the target file if it already exists. If the operation succeeds, a success message is printed. If the target file exists and the REPLACE_EXISTING option isn't used, a FileAlreadyExistsException is thrown. Other I/O errors are also caught and handled.

Comments