package com.softeem.homework;
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;
import java.io.InputStream;
import java.io.OutputStream;
@SuppressWarnings("unused")
public class CopyWenjian {
public static void main(String[] args) throws IOException {
File file1 = new File("D:\\Program Files\\feiq\\Recv Files\\lesson_10");//源目录
File file2 = new File("D:\\拷贝文件夹");//新目录
//递归拷贝文件
listCopyAll(file1,file2);
}
//递归拷贝文件
private static void listCopyAll(File dir1, File dir2) throws IOException {
//新目录
dir2.mkdir();
//获取源目录文件对象列表
File[] files = dir1.listFiles();
//file源目录的最近一级子目录及文件
for (File file : files) {
//如果是目录就继续遍历
if(file.isDirectory()){
//根据file传入new dir2子目录地址进行创建
listCopyAll(file,new File(dir2.getAbsolutePath()+File.separator+file.getName()));//在自身目录上衔接目录
}else{
//如果是文件就创建
File newFile = new File(dir2.getAbsolutePath()+File.separator+file.getName());
newFile.createNewFile();
//拷贝文件
copyFile(file,newFile);
}
}
}
//copy文件
private static void copyFile(File file, File newFile) throws IOException {
//读取源文件信息
InputStream st = new FileInputStream(file);
BufferedInputStream bis = new BufferedInputStream(st);
//写入新文件信息
OutputStream st1 = new FileOutputStream(file);
BufferedOutputStream bos = new BufferedOutputStream(st1);
int len=0;
byte[] b = new byte[1024];
while((len=bis.read(b))!=-1){
bos.write(b, 0, len);
bos.flush();
}
bos.close();
bis.close();
}
}