Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

Files.copy()

Copies a file. By default it does not overwrite an existing file.

Available since: Java 7

Syntax

public static Path copy(Path source, Path target, CopyOption... options)

Parameters

ParameterTypeDescription
sourcePathWhat to copy.
targetPathThe path of the copy, including the file name.
optionsCopyOption...Optional: REPLACE_EXISTING, COPY_ATTRIBUTES.

Return value

PathThe path of the copy.

Examples

A backup copy of a file; the original stays where it is:

void main() throws IOException {
    Path dir = Files.createTempDirectory("demo");
    Path source = Files.writeString(dir.resolve("notes.txt"), "Buy milk");
 
    Path copy = Files.copy(source, dir.resolve("notes-backup.txt"));
    IO.println(Files.readString(copy));
    IO.println(Files.exists(source));
}

Output:

Buy milk
true

Overwriting an existing file requires REPLACE_EXISTING:

void main() throws IOException {
    Path dir = Files.createTempDirectory("demo");
    Path a = Files.writeString(dir.resolve("a.txt"), "new");
    Path b = Files.writeString(dir.resolve("b.txt"), "old");
 
    Files.copy(a, b, StandardCopyOption.REPLACE_EXISTING);
    IO.println(Files.readString(b));
}

Output:

new

Notes

Without REPLACE_EXISTING, copying over an existing file throws FileAlreadyExistsException. A folder is copied without its contents — to copy a tree, walk it with Files.walk(). There are overloads for streams: Files.copy(inputStream, path) saves data to a file, Files.copy(path, outputStream) sends a file to a stream.

See also

  • Files.move() — Moves or renames a file or a folder.
  • Files.delete() — Deletes a file or an empty folder. deleteIfExists() does not throw if the file is missing.
  • Files.exists() — Checks whether a file or folder exists. Related: isDirectory(), isRegularFile(), size().
  • Path.of() — Creates a Path object — a path to a file or folder.

In the tutorial

  • Files and paths — Working with the file system in Java — Path, Files.exists, creating folders and files, size, copying, moving, deleting and listing files.

Thanks for reading!

Donate to the site — we work hard for you.