package 练习;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
//复制整个文件夹
public class fuzhiFolder {
public static void main(String[] args) throws IOException {
File f = new File("C:\\Users\\86187\\Desktop\\蓝桥资料\\学习资料"); //原文件夹
String newPath = "E:\\新建文件夹"; //复制到的目的目录
mkdirFile(f,newPath); //调用mkdirFile方法
}
public static void mkdirFile(File file,String path) throws IOException {
File[] listFiles = file.listFiles(); //得到file文件夹下的所有文件及目录
for (File f1 : listFiles) { //循环处理所有文件及目录f1
if(f1.isDirectory()) { //如果f1是文件夹
File newFile = new File(path,f1.getName()); //新建一个文件夹对象(目的目录路径+f1的文件名)
newFile.mkdir(); //新建文件夹
mkdirFile(f1,newFile.getAbsolutePath()); //递归调用本方法处理新建文件夹
}else {
copyFile(f1,new File(path,f1.getName())); //如果是文件,调用copyFile方法
}
}
}
public static void copyFile(File descfile, File newfile) throws IOException {
FileInputStream in = new FileInputStream(descfile); //新建字节输入流in
BufferedInputStream bfin = new BufferedInputStream(in); //新建缓冲的字节输入流bfin,包含住in
FileOutputStream out = new FileOutputStream(newfile); //新建字节输出流out
BufferedOutputStream bfout = new BufferedOutputStream(out); //新建缓冲的字节输出流bfout,包含住out
byte[] b = new byte[1024]; //新建字节数组,作为二级缓冲区
int len;
while ((len = bfin.read(b))!= -1) { //将读取到的b长度的内容赋给len,并判断是否为空
bfout.write(b,0,len); //不为空的话,将读取到的内容len放到b中,0是开始位置。再写入
}
//关闭流,只需要关闭最外层流。先关输出,再关输入
bfout.close();
bfin.close();
}
}