java 如何复制文件
使用 Files.copy() 方法(Java NIO)
Java NIO 的 Files.copy() 方法提供高效的文件复制功能,支持路径操作和选项配置。
import java.nio.file.*;
Path source = Paths.get("source.txt");
Path target = Paths.get("target.txt");
Files.copy(source, target, StandardCopyOption.REPLACE_EXISTING);
StandardCopyOption.REPLACE_EXISTING 参数确保覆盖已存在的目标文件。
使用 FileInputStream 和 FileOutputStream(传统 IO)
通过字节流逐字节读取和写入文件,适合需要自定义缓冲大小的场景。

import java.io.*;
try (InputStream in = new FileInputStream("source.txt");
OutputStream out = new FileOutputStream("target.txt")) {
byte[] buffer = new byte[1024];
int length;
while ((length = in.read(buffer)) > 0) {
out.write(buffer, 0, length);
}
}
使用 try-with-resources 确保流自动关闭,避免资源泄漏。
使用 FileChannel 传输(高性能)
FileChannel.transferTo() 方法利用操作系统零拷贝技术提升大文件复制效率。

import java.nio.channels.*;
import java.io.*;
try (FileInputStream fis = new FileInputStream("source.txt");
FileOutputStream fos = new FileOutputStream("target.txt")) {
FileChannel sourceChannel = fis.getChannel();
FileChannel targetChannel = fos.getChannel();
sourceChannel.transferTo(0, sourceChannel.size(), targetChannel);
}
此方法特别适合处理大型文件,减少内核态与用户态间的数据拷贝。
使用 Apache Commons IO
引入 commons-io 依赖后,FileUtils.copyFile() 提供单行代码实现。
import org.apache.commons.io.FileUtils;
FileUtils.copyFile(new File("source.txt"), new File("target.txt"));
需确保项目中包含以下 Maven 依赖:
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.11.0</version>
</dependency>
错误处理注意事项
无论采用哪种方法,都应捕获 IOException 并处理可能出现的异常情况,例如文件不存在、权限不足或磁盘空间不足等问题。建议在代码中添加适当的日志记录或用户提示。






