Java Files.copy
Copy file contents to a new destination or transfer bytes between a file and a stream.
A simple example
Files.copy
- Start with Source file containing A
- Do this Copy to a second file
- Result Both contain A
Syntax
public static Path copy(Path source, Path target, CopyOption... options) throws IOException
JDK 21 declarations (3)
Run these examples in Java
Save one example at a time as Main.java. Use JDK 21.
java Main.javaHand a copy of a receipt to the customer
A shop needs a customer copy of a receipt and a separate original for the ledger. The two initially contain the same text, but a later annotation on the customer copy should leave the ledger untouched.
import java.nio.file.*;
class Main {
public static void main(String[] args) throws Exception {
Path desk = Files.createTempDirectory("file-lesson-");
try {
Path ledger = Files.writeString(desk.resolve("ledger.txt"), "paid");
Path copy = Files.copy(ledger, desk.resolve("customer.txt"));
Files.writeString(copy, "paid - collected");
System.out.println(Files.readString(ledger));
System.out.println(Files.readString(copy));
} finally {
try (var paths = Files.walk(desk)) {
for (Path p : paths.sorted(java.util.Comparator.reverseOrder()).toList())
Files.deleteIfExists(p);
}
}
}
}
paid paid - collected
The destination is an independent file. Updating it does not edit the source.
Count the bytes sent to a label printer
A printer adapter accepts an output stream instead of a filename. Send a short label to an in-memory stand-in and use the number returned by copy to check how many bytes were transferred.
import java.nio.file.*;
import java.io.*;
class Main {
public static void main(String[] args) throws Exception {
Path desk = Files.createTempDirectory("file-lesson-");
try {
Path label = Files.writeString(desk.resolve("label.txt"), "A17");
var printer = new ByteArrayOutputStream();
System.out.println(Files.copy(label, printer));
System.out.println(printer.toString(java.nio.charset.StandardCharsets.UTF_8));
} finally {
try (var paths = Files.walk(desk)) {
for (Path p : paths.sorted(java.util.Comparator.reverseOrder()).toList())
Files.deleteIfExists(p);
}
}
}
}
3 A17
The byte count and the captured text are both available to the caller.
Prepare a gallery label
A curator stores a short UTF-8 caption beside an exhibit. Make a second copy for the afternoon shift. Which text does the new file contain?
What to watch for
Copying a directory with this call does not recursively copy its children. Existing destinations require an explicit replacement policy.