**
Java使用IO复制文件夹下所有项目到另一个文件夹下
package foundation.IO;
import foundation.IOUtils.IoUtils;
import java.io.*;
/**
* @author {周江涛}
* @date 2022/10/29 10:13
*/
public class IoTest01 extends IoUtils {
/**复制图片,视频*/
public static void main(String[] args) throws IOException{
// File src= new File("E:\\蚂蚁课堂每特教育2022Java零基础课程精华版本\\05.javase之IO流相关"); //源文件夹
File src= new File("D:\\mayikt");
File desc = new File("D:\\meite"); //目标文件夹
if (!desc.exists()) { //如果目标文件夹不存在
desc.mkdirs(); //创建目标文件夹
}
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数组用于存储文件
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为源路径
}
}
}
}
}
文章原创地址为:https://blog.csdn.net/qq_45886144/article/details/124492923