实现说明
逻辑集中在类 ChannelCopy里。
while (copied < size) 承担全部的逐项处理。不需要 finally——try 头部声明的资源按相反顺序自行关闭。
使用要点
- 演示输出是带标签的(
size=、identical:),每个操作都会留下自己的一行标注。
常见问题
运行「FileChannel.transferTo 通道间拷贝」会打印什么?
不用做任何设置,直接把文件跑完——输出里的 size=、identical: 标签标明各步骤。
核心语句
copied += from.transferTo(copied, size - copied, to);
代码示例
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);
}
}