package cn.idcast4;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
/* 步骤很重要,知道步骤就知道怎么写代码
* 需求:复制多级文件夹
* 分析:
* A、封装数据源File
* B、封装目的地File 目的地一定要存在
* C、判断该File是文件夹还是文件
* a、是文件夹
* 1、就在目的地目录下创建文件夹
* 2、获取该File对象的所有文件或者文件夹File对象
* 3、遍历得到每一个File对象
* 4、回到C
* b、是文件
* 就复制(字节流)
*
*/
public class Day17 {
public static void main(String[] args) throws IOException {
File srcFile = new File("d:\\java");
File destFile = new File("c:\\");
// 注意看C C步骤要回到C步骤,属于递归,得写个复制文件夹的功能
copyFolder(srcFile, destFile);
}
private static void copyFolder(File srcFile, File destFile)
throws IOException {
// TODO Auto-generated method stub
if (srcFile.isDirectory()) {
// 是文件夹,就得先得到文件夹的路径
File newFolder = new File(destFile, srcFile.getName());
// 创建文件夹
newFolder.mkdir();
File[] fileArray = srcFile.listFiles();
for (File file : fileArray) {
copyFolder(file, newFolder);
}
} else {
// 是文件,先得到文件的路径,然后进行复制
File newFile = new File(destFile, srcFile.getName());
copyFile(srcFile, newFile);
}
}
private static void copyFile(File srcFile, File newFile) throws IOException {
// TODO Auto-generated method stub
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(
srcFile));
BufferedOutputStream bos = new BufferedOutputStream(
new FileOutputStream(newFile));
byte[] bys = new byte[1024];
int len = 0;
while ((len = bis.read()) != -1) {
bos.write(bys, 0, len);
}
bis.close();
bos.close();
}
}