import java.io.*;
public class IO {
public static void main(String[] args) throws IOException{
File src= new File("sorceFile\"); //源文件夹
File desc = new File("targetFile"); //目标文件夹
long start = System.currentTimeMillis();
copyFile(src, desc); //复制文件夹
long end = System.currentTimeMillis();
System.out.println("复制文件夹耗时:" + (end - start) + "ms");
}
public static void copyFile(File src, File desc) throws IOException {
if (src.isFile()) { //如果是文件
FileInputStream fis = new FileInputStream(src);
String path = desc.getAbsolutePath();
FileOutputStream fos = new FileOutputStream(path);
BufferedInputStream bis = new BufferedInputStream(fis);
BufferedOutputStream bos = new BufferedOutputStream(fos);
byte[] b = new byte[1024*1024];
int len = 0;
while ((len = bis.read(b)) != -1) {
bos.write(b, 0, len);
}
bos.flush();
bos.close();
bis.close();
}else { //如果是文件夹
File[] files = src.listFiles(); //获取文件夹下的所有文件
if (files.length == 0) { //如果文件夹为空
String srcPath = src.getName(); //获取文件夹名称
//拿到新文件夹的路径,新文件夹的路径为:目标文件夹的路径+文件夹名称
String descPath = (desc.getAbsolutePath().endsWith("\") ? desc.getAbsolutePath() : desc.getAbsolutePath() + "\" + srcPath);
File newFile = new File(descPath); //创建新文件夹
if (!newFile.exists()) { //如果新文件夹不存在
newFile.mkdirs(); //创建新文件夹
}
} else { //如果文件夹不为空
for(File f : files) { //遍历文件夹下的所有文件
String srcPath = f.getName(); //获取文件或文件夹的名称
String descPath = ""; //新文件夹的路径
if (f.isFile()) { //如果是文件
descPath = desc.getAbsolutePath() + "\" + f.getName(); //新文件夹的路径为:目标文件夹的路径+文件夹名称
}
if (f.isDirectory()) { //如果是文件夹
//拿到新文件夹的路径,新文件夹的路径为:目标文件夹的路径+文件夹名称
descPath = (desc.getAbsolutePath().endsWith("\") ? desc.getAbsolutePath() : desc.getAbsolutePath() + "\" + srcPath);
}
File newFile = new File(descPath); //创建新文件夹
if (f.isDirectory()) { //如果是文件夹
if (!newFile.exists()) { //如果新文件夹不存在
newFile.mkdirs(); //创建新文件夹
}
}
copyFile(f, newFile); //递归调用,此时拿到的newFile为目标路径,f为源路径
}
}
}
}
}