【Java】复制 源文件/文件夹 至目标文件夹
- 对于源文件,直接使用Java NIO中提供的FileChannel进行复制,要注意的是在目标文件夹中需要先创建不存在的文件夹才能复制文件。
private static void copyFile(File fromFile, File toFile) throws IOException {
if (!toFile.exists()) toFile.getParentFile().mkdirs();
FileChannel inputChannel = null;
FileChannel outputChannel = null;
try {
inputChannel = new FileInputStream(fromFile).getChannel();
outputChannel = new FileOutputStream(toFile).getChannel();
outputChannel.transferFrom(inputChannel, 0, inputChannel.size());
} finally {
Objects.requireNonNull(inputChannel).close();
Objects.requireNonNull(outputChannel).close();
}
}
- 对于源文件夹,通过递归进行遍历,调用copyFile方法进行文件复制。
private final Logger logger = LoggerFactory.getLogger(this.getClass());
public void copyToDir(File from, File toDir) {
if (from == null || toDir == null) {
logger.error("源路径或目标路径为空,无法完成复制,请检查传入参数。");
return;
}
if (!from.exists()) {
logger.error("源路径不存在,无法完成复制。");
return;
}
if (!toDir.isDirectory()) {
logger.error("目标路径不是文件夹类型,无法完成复制。");
return;
}
if (!toDir.exists()) {
boolean mkdirs = toDir.mkdirs();
}
if (from.isFile()) {
try {
copyFile(from, new File(toDir.getAbsolutePath() + File.separator + from.getName()));
} catch (IOException e) {
e.printStackTrace();
logger.error("复制文件错误 --->>> " + from.getAbsolutePath() + e);
}
} else if (from.isDirectory()) {
File newToDir = new File(toDir.getAbsolutePath() + File.separator + from.getName());
newToDir.mkdirs();
File[] froms = from.listFiles();
if (froms == null) return;
for (File file : froms) {
copyToDir(file, newToDir);
}
} else {
logger.error("复制文件失败 --->>> 原因未知");
}
}