java实现文件夹复制
时间: 2023-08-28 11:07:51 浏览: 44
可以使用Java的IO库中的File类来实现文件夹的复制,具体可以参考以下代码:
```
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;
public class FolderCopy {
public static void main(String[] args) throws IOException {
File source = new File("sourceFolder");
File dest = new File("destFolder");
// 如果目标文件夹不存在,则创建
if (!dest.exists()) {
dest.mkdir();
}
// 获取源文件夹下的所有文件和子文件夹
File[] files = source.listFiles();
// 遍历文件并复制
for (File file : files) {
if (file.isDirectory()) {
// 递归复制子文件夹
copyFolder(file.getPath(), dest.getPath() + File.separator + file.getName());
} else {
// 复制文件
FileChannel in = null;
FileChannel out =null;
try {
in = new FileInputStream(file).getChannel();
out = new FileOutputStream(dest.getPath() + File.separator + file.getName()).getChannel();
in.transferTo(0, in.size(), out);
} finally {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
}
}
}
System.out.println("文件夹复制完成!");
}
public static void copyFolder(String sourceDir, String targetDir) throws IOException {
(new File(targetDir)).mkdirs();
File[] file = (new File(sourceDir)).listFiles();
for (int i = 0; i < file.length; i++) {
if (file[i].isFile()) {
File sourceFile = file[i];
File targetFile = new File(new File(targetDir).getAbsolutePath() + File.separator + file[i].getName());
FileInputStream in = new FileInputStream(sourceFile);
FileOutputStream out = new FileOutputStream(targetFile);
byte[] buffer = new byte[1024 * 5];
int len;
while ((len = in.read(buffer)) != -1) {
out.write(buffer, 0, len);
}
out.flush();
out.close();
in.close();
}
if (file[i].isDirectory()) {
String sourcePath = sourceDir + "/" + file[i].getName();
String targetPath = targetDir + "/" + file[i].getName();
copyFolder(sourcePath, targetPath);
}
}
}
}
```