public static void copyDir(final File src, final File dest) throws IOException {
dest.mkdirs();
File[] files = src.listFiles();
int j = files.length; // cache the length so it doesn't need to be looked up over and over in the loop
for (int i = 0; i < j; i++) {
File file = files[i];
if (file.isDirectory()) {
copyDir(file, new File(dest, file.getName()));
} else {
copyFile(file, new File(dest, file.getName()));
}
}
}
public static void copyFile(final File src, final File dest) throws IOException {
dest.getParentFile().mkdirs();
dest.createNewFile();
FileChannel sourceChannel = new FileInputStream(src).getChannel();
FileChannel targetChannel = new FileOutputStream(dest).getChannel();
sourceChannel.transferTo(0, sourceChannel.size(), targetChannel);
sourceChannel.close();
targetChannel.close();
}
dest.mkdirs();
File[] files = src.listFiles();
int j = files.length; // cache the length so it doesn't need to be looked up over and over in the loop
for (int i = 0; i < j; i++) {
File file = files[i];
if (file.isDirectory()) {
copyDir(file, new File(dest, file.getName()));
} else {
copyFile(file, new File(dest, file.getName()));
}
}
}
public static void copyFile(final File src, final File dest) throws IOException {
dest.getParentFile().mkdirs();
dest.createNewFile();
FileChannel sourceChannel = new FileInputStream(src).getChannel();
FileChannel targetChannel = new FileOutputStream(dest).getChannel();
sourceChannel.transferTo(0, sourceChannel.size(), targetChannel);
sourceChannel.close();
targetChannel.close();
}
本文介绍了一种用Java实现的文件及目录复制的方法。通过递归方式处理目录,并使用FileChannel进行文件内容的高效复制。文章提供了完整的代码示例,包括复制文件和整个目录结构。
6万+

被折叠的 条评论
为什么被折叠?



