拷贝目录的思路:对要拷贝的文件夹进行遍历,如果遍历到文件夹就在目标文件夹生成该文件夹。如果遍历到文件就使用IO流拷贝该文件,到此返回上一层的迭代。
package com.fan;
import java.util.Date;
import java.io.*;
import java.util.*;
public class main {
public static void main(String[] args) throws FileNotFoundException,IOException {
File f1=new File("D:\\src");
File f2=new File("C:\\");
copyDir(f1,f2);
}
public static void copyDir(File f1,File f2) throws IOException {
/*
* 如果f1是文件的话,创建一个输入流和一个输出流来复制文件的内容
* */
if (f1.isFile()){
FileInputStream fis =new FileInputStream(f1.getAbsoluteFile());
String desPath=(f2.getAbsolutePath().endsWith("\\")?f2.getAbsolutePath():f2.getAbsolutePath()+"\\")+f1.getAbsolutePath().substring(3);
// f2的路径是目标文件夹,先判断其最后是不是\\,不是就加上。再加上f1的路径去掉盘符,就组成了复制文件的路径
FileOutputStream fos=new FileOutputStream(desPath);
byte[] b=new byte[1024*1024];
int readCount=0;
while((readCount=fis.read(b))!=-1){
fos.write(b,0,readCount);
}
fos.flush();
fis.close();fos.close();
// 迭代到文件结束迭代
return;
}
// 获取的全部目录
File[] files=f1.listFiles();
for (File file:files){
// 迭代到目录,就复制一个目录
System.out.println("源路径"+file.getAbsolutePath());
if (file.isDirectory()){
String desPath=(f2.getAbsolutePath().endsWith("\\")?f2.getAbsolutePath():f2.getAbsolutePath()+"\\")+file.getAbsolutePath().substring(3);
System.out.println("目标路径"+desPath);
File newFile=new File(desPath);
if (!newFile.exists()) {
newFile.mkdirs();
}
}
// 将file不断迭代下去,相当于一层层下降直到文件,f2并没有变
copyDir(file,f2);
}
}
}