复制多级文件夹关键在于递归调用,文件夹不能被复制,只能遇到后重新创建,同样输出流写出文件时,会自动创建文件,完成单个文件的复制;
import java.io.*;
public class MyTest {
public static void main(String[] args) throws IOException {
File srcFolder = new File("C:\\Users\\Administrator\\Desktop\\test1");
File targetFolder = new File("C:\\Users\\Administrator\\Desktop\\copytest1");
if (!targetFolder.exists()) {
targetFolder.mkdirs();
}
copyFolder(srcFolder, targetFolder);
System.out.println("复制完成");
}
private static void copyFolder(File srcFolder, File targetFolder) throws IOException {
File[] files = srcFolder.listFiles();
for (File f : files) {
if (f.isFile()) {
copyFiles(f, targetFolder);
}else{
File mbFolder = new File(targetFolder, f.getName());
if (!mbFolder.exists()) {
mbFolder.mkdirs();
}
copyFolder(f,mbFolder);
}
}
}
private static void copyFiles(File f, File targetFolder) throws IOException {
FileInputStream in = new FileInputStream(f);
File file = new File(targetFolder, f.getName());
FileOutputStream out = new FileOutputStream(file);
int len = 0;
byte[] bytes = new byte[1024 * 8];
while ((len = in.read(bytes)) != -1) {
out.write(bytes, 0, len);
out.flush();
}
out.close();
in.close();
}
}