Course contentsShow
← Java
Lesson 2056 of 2,87041. NIO.2 and the Path APIFree lesson

CopyOption: REPLACE_EXISTING and COPY_ATTRIBUTES

Use StandardCopyOption to control copy behavior: replacing existing files and preserving file attributes.

CopyOption: REPLACE_EXISTING and COPY_ATTRIBUTES

What you'll learn: How to control file copying behavior using StandardCopyOption constants to handle existing files and preserve metadata.

The Core Idea

When copying files with Files.copy, you can pass CopyOption arguments to control exactly how the copy operation behaves. The two most common options are:

  • REPLACE_EXISTING: Overwrites the destination file if it already exists (otherwise, copy fails with an exception)
  • COPY_ATTRIBUTES: Preserves file attributes like timestamps, permissions, and other metadata from the source file

Without these options, Files.copy won't overwrite existing files and won't preserve attributes.

Using CopyOptions

import java.nio.file.*;
import static java.nio.file.StandardCopyOption.*;

// Basic copy - fails if destination exists
Files.copy(source, destination);

// Replace existing file
Files.copy(source, destination, REPLACE_EXISTING);

// Preserve file attributes (timestamps, permissions, etc.)
Files.copy(source, destination, COPY_ATTRIBUTES);

// Combine both options
Files.copy(source, destination, REPLACE_EXISTING, COPY_ATTRIBUTES);

Real-World Analogy

Think of copying a document in an office. REPLACE_EXISTING is like saying "yes, overwrite the old version in that folder." COPY_ATTRIBUTES is like keeping the original document's creation date and author information on the copy, rather than treating it as a brand-new document.

When to Use Each

  • Use REPLACE_EXISTING when updating files or when you want copy operations to succeed even if the file exists
  • Use COPY_ATTRIBUTES when file metadata matters (backups, migrations, or preserving timestamps)
  • Combine both for full-featured file copying that mimics native OS copy behavior

Key Takeaway: StandardCopyOption.REPLACE_EXISTING and COPY_ATTRIBUTES give you fine-grained control over file copying—whether to overwrite destinations and whether to preserve the source file's metadata.