下面的示例向您展示如何使用java.nio.channels.FileChannel该类复制文件。
package org.nhooo.example.io;
import java.io.*;
import java.nio.channels.FileChannel;
public class FileCopy {
public static void main(String[] args) {
//// 定义源文件和目标文件
File source = new File("D:/Temp/source.txt");
File target = new File("D:/Temp/target.txt");
// 创建源通道和目标通道
try (FileChannel sourceChannel = new FileInputStream(source).getChannel();
FileChannel targetChannel = new FileOutputStream(target).getChannel()) {
// 将数据从源通道复制到目标通道
targetChannel.transferFrom(sourceChannel, 0, sourceChannel.size());
} catch (Exception e) {
e.printStackTrace();
}
}
}