FileChannel TransferTo Channel Copy

transferTo hands bytes between channels without a user-space buffer; a call may move fewer bytes than requested, so the loop advances by the returned count.

JavaData Integrity

Code

snippet
import java.io.IOException;
import java.nio.channels.FileChannel;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;

public class ChannelCopy {

    public static void main(String[] args) throws IOException {
        Path source = Files.createTempFile("audit-", ".log");
        Path target = Files.createTempFile("audit-copy-", ".log");
        Files.writeString(source, "tx 1 ok\ntx 2 ok\ntx 3 rolled back\n");

        try (FileChannel from = FileChannel.open(source, StandardOpenOption.READ);
             FileChannel to = FileChannel.open(target,
                     StandardOpenOption.CREATE, StandardOpenOption.WRITE)) {
            long size = from.size();
            long copied = 0;
            while (copied < size) {
                // A single transferTo call may move fewer bytes: advance by the return value until done
                copied += from.transferTo(copied, size - copied, to);
            }
            System.out.println("size=" + size + " bytes, transferred=" + copied);
        }

        System.out.println("identical: " + (Files.mismatch(source, target) == -1));
        Files.deleteIfExists(source);
        Files.deleteIfExists(target);
    }
}

How the snippet works

FileChannel TransferTo Channel Copy is built around the class ChannelCopy.

Repetition is confined to while (copied < size) — the rest of the file is straight-line. Resources are declared in a try-with-resources header, so they close on every exit path without a finally block.

Applying it

Printed lines come prefixed — size=, identical: — when the file runs.

Statements that matter

copied += from.transferTo(copied, size - copied, to);

Interactive Tools for This Topic

FAQ

What does FileChannel TransferTo Channel Copy print when run?
Running the file directly is enough — expect labeled output lines such as `size=`, `identical:`.