public class 复制多级文件夹 {
public static void main(String[] args) throws IOException {
//封装源文夹
File srcFolder = new File("E:\\xuanxuanaiJava");
//封装目标文件夹
File targetFolder = new File("C:\\Users\\46188\\Desktop\\xuanxuanaiJava");
//如果目标文件夹不存在,则创建
if (!targetFolder.exists()) {
targetFolder.mkdirs();
}
//复制目录
copyFolder(srcFolder, targetFolder);
}
//复制目录
private static void copyFolder(File srcFolder, File targetFolder) throws IOException {
//遍历源文件夹所有的文件,复制到目标文件夹下
File[] files = srcFolder.listFiles();
for (File f : files) {
//如果f是子文件就直接复制
if (f.isFile()) {
//复制文件
copyFiles(f, targetFolder);
} else {
//递归
//如果是文件夹,就创建文件夹,然后递归复制目录
File ff = new File(targetFolder.getAbsolutePath(), f.getName());
ff.mkdirs();
copyFolder(f,ff);
}
}
}
//复制文件
private static void copyFiles(File f, File targetFolder) throws IOException {
FileInputStream in = new FileInputStream(f);
FileOutputStream out = new FileOutputStream(new File(targetFolder, f.getName()));
byte[] bytes = new byte[1024];
int len = 0;
while ((len = in.read(bytes)) != -1) {
out.write(bytes, 0, len);
out.flush();
}
in.close();
out.close();
}
}
//注意:java的io流只能读取文件,不能读取文件夹,文件夹只能创建出来。
09-21
253