Java Files copy() Method

Beginner
6 min read
Updated: Nov 2026
3 examples
Java 7+

Definition

In Java, Files.copy(source, target) copies the file source to the new path target. By default it refuses to overwrite: if target exists it throws FileAlreadyExistsException, unless you pass StandardCopyOption.REPLACE_EXISTING.

Two more overloads connect files and streams: copy(InputStream, Path) saves a stream into a file and copy(Path, OutputStream) sends a file into a stream; both return the byte count.

A static method of the final utility class java.nio.file.Files, available since Java 7. Call it on the class name, as in Files.copy(...), after import java.nio.file.Files;. You never create a Files object.

Syntax

Three overloads; options are optional:

Java
Files.copy(notes, backup);                                      // fails if backup exists
Files.copy(notes, backup, StandardCopyOption.REPLACE_EXISTING);  // overwrite
long n = Files.copy(inputStream, target);                        // stream to file
long m = Files.copy(source, outputStream);                       // file to stream
CallWhat it does
REPLACE_EXISTINGOverwrite an existing target (an empty folder is replaced too).
COPY_ATTRIBUTESAlso copy attributes; at least the last-modified time.
LinkOption.NOFOLLOW_LINKSCopy a symbolic link itself, not its target.

Since Java 7. Copying a folder creates an empty folder: the entries inside are not copied. To copy a tree, walk it and copy each entry (Example 3).

Library declarations
Java
public static Path copy(Path source, Path target, CopyOption... options) throws IOException
public static long copy(InputStream in, Path target, CopyOption... options) throws IOException
public static long copy(Path source, OutputStream out) throws IOException

Parameters

ParameterDescription
source / inThe file, or open stream, to read from (streams are not closed).
target / outThe path to create, or the stream to write to.
optionsREPLACE_EXISTING, COPY_ATTRIBUTES, NOFOLLOW_LINKS; the stream overload accepts only REPLACE_EXISTING.

Return Value

Return ValueDescription
Path(Path to Path) the target.
long(Stream overloads) the number of bytes read or written.

Compare with Similar Methods

Copying, moving, and linking:

MethodHow it differs
move()Relocates or renames; the source is gone afterwards.
createLink()A second name for the same data, not a separate copy.
walk()Needed to copy a folder together with its contents.

Java Examples

Example 1 — Back Up a File, Then Refresh the Backup

A plain copy fails once the backup exists; REPLACE_EXISTING overwrites it.

Java
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.FileAlreadyExistsException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;

public class CopyReplace {
    public static void main(String[] args) throws IOException {
        Path dir = Files.createTempDirectory("demo");
        Path notes = dir.resolve("notes.txt");
        Path backup = dir.resolve("notes.bak");
        Files.write(notes, "draft 1".getBytes(StandardCharsets.UTF_8));
        Files.copy(notes, backup);
        Files.write(notes, "draft 2".getBytes(StandardCharsets.UTF_8));
        try {
            Files.copy(notes, backup);
        } catch (FileAlreadyExistsException e) {
            System.out.println("Plain copy refused: notes.bak exists");
        }
        System.out.println("Backup before: " + new String(Files.readAllBytes(backup), StandardCharsets.UTF_8));
        Files.copy(notes, backup, StandardCopyOption.REPLACE_EXISTING);
        System.out.println("Backup after:  " + new String(Files.readAllBytes(backup), StandardCharsets.UTF_8));
        Files.delete(backup);
        Files.delete(notes);
        Files.delete(dir);
    }
}

How It Works

  1. First backup. notes.bak does not exist yet, so the plain copy creates it holding draft 1.
  2. The source changes. notes.txt is rewritten with draft 2, and a second plain copy now meets an existing target and throws FileAlreadyExistsException.
  3. Old data survives the refusal. The backup still says draft 1, because a refused copy writes nothing.
  4. Explicit overwrite. With REPLACE_EXISTING the copy replaces notes.bak, which now matches draft 2.

Example 2 — Copy from an InputStream and into an OutputStream

Save bytes from a stream into a file, then send the file into an in-memory output stream. Both overloads return a byte count.

Java
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;

public class CopyStreams {
    public static void main(String[] args) throws IOException {
        Path dir = Files.createTempDirectory("demo");
        Path greeting = dir.resolve("greeting.txt");
        byte[] data = "Hello, NIO!".getBytes(StandardCharsets.UTF_8);
        long intoFile = Files.copy(new ByteArrayInputStream(data), greeting);
        System.out.println("Stream to file: " + intoFile + " bytes");
        ByteArrayOutputStream sink = new ByteArrayOutputStream();
        long intoStream = Files.copy(greeting, sink);
        System.out.println("File to stream: " + intoStream + " bytes");
        System.out.println("Stream holds: " + new String(sink.toByteArray(), StandardCharsets.UTF_8));
        Files.delete(greeting);
        Files.delete(dir);
    }
}

How It Works

  1. Any InputStream works. A ByteArrayInputStream stands in for a download or a resource; copy reads it to the end and creates greeting.txt.
  2. Counting bytes. "Hello, NIO!" has 11 ASCII characters, so 11 bytes travel each way.
  3. File into a stream. copy(Path, OutputStream) writes the file into sink. Neither overload closes the stream you pass, so real file or network streams belong in try-with-resources.

Example 3 — Folders Copy Empty: Walk the Tree Instead

Copying a folder directly gives an empty folder. Walking the source and copying every entry gives a full copy.

Java
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class CopyTree {
    public static void main(String[] args) throws IOException {
        Path dir = Files.createTempDirectory("demo");
        Path site = Files.createDirectory(dir.resolve("site"));
        Files.write(site.resolve("index.html"), "Hi".getBytes(StandardCharsets.UTF_8));
        Path css = Files.createDirectory(site.resolve("css"));
        Files.write(css.resolve("style.css"), "h1{}".getBytes(StandardCharsets.UTF_8));
        Path shallow = Files.copy(site, dir.resolve("shallow"));
        try (Stream<Path> s = Files.list(shallow)) {
            System.out.println("Shallow copy entries: " + s.count());
        }
        Path deep = dir.resolve("deep");
        List<Path> sources;
        try (Stream<Path> s = Files.walk(site)) {
            sources = s.sorted().collect(Collectors.toList());
        }
        for (Path from : sources) {
            Files.copy(from, deep.resolve(site.relativize(from)));
        }
        List<String> copied;
        try (Stream<Path> s = Files.walk(deep)) {
            copied = s.filter(p -> !p.equals(deep))
                      .map(p -> deep.relativize(p).toString().replace('\\', '/'))
                      .sorted().collect(Collectors.toList());
        }
        System.out.println("Deep copy: " + copied);
        List<Path> all;
        try (Stream<Path> s = Files.walk(dir)) {
            all = s.sorted(Comparator.reverseOrder()).collect(Collectors.toList());
        }
        for (Path p : all) {
            Files.delete(p);
        }
    }
}

How It Works

  1. Shallow by design. Files.copy(site, shallow) creates the folder shallow but none of its entries, so listing it counts 0.
  2. Parents before children. Sorting the walked paths puts site before site/css and site/css before its file, so each target folder exists before something is copied into it.
  3. Map each path. site.relativize(from) gives the part below site (empty for site itself), and deep.resolve(...) places it under deep.
  4. Sorted report, reverse cleanup. The copied names are sorted because walk order is not fixed, and the final reverse-order walk deletes everything, deepest first.

Frequently Asked Questions

Pass StandardCopyOption.REPLACE_EXISTING. Without it the call throws FileAlreadyExistsException when the target exists.
No. It creates an empty directory at the target. Walk the source and copy each entry to copy the whole tree.
It copies file attributes too: at least the last-modified time, and others such as permissions where the platform supports it.
No. It reads the stream to the end but leaves closing to you.
No. A failure part-way can leave a partial target. ATOMIC_MOVE exists only for move.

Next: Files.createDirectories()

Create a folder and every missing parent; no error if the folder already exists.

createDirectories() tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

7 people found this page helpful