复制多级文件夹下的文件
案例描述:
在 D:\iofile 文件夹下存在多级文件夹及文件,希望把这些全部复制到新位置(day10\iofile)
参考思路:复制单级文件夹下的文件 - 鹿先森JIAN - 博客园 (cnblogs.com)
import java.io.*; // 用到了递归思想 public class CopyFolders { public static void main(String[] args) throws IOException { //1.描述数据源文件夹File对象 File srcFolder = new File("D:\\iofile"); //2.获取数据源文件夹的名称 String srcFolderName = srcFolder.getName(); // iofile //3.构造目的地文件夹File对象 File destFolder = new File("day10", srcFolderName); // day10\iofile //4.判断不存在则创建该文件夹 if (!destFolder.exists()){ destFolder.mkdir(); // 创建一级文件夹:day10\iofile } copyFolder(srcFolder,destFolder); } public static void copyFolder(File srcFolder,File destFolder) throws IOException{ //5.遍历数据源文件夹,拿到下面的第一级的内容的File对象 File[] files = srcFolder.listFiles(); for (File file : files) { if (file.isDirectory()){ // 是否为文件夹 String srcZiFolderName = file.getName(); // 获取该文件夹名 File destZiFolder = new File(destFolder, srcZiFolderName); // 拼接 destZiFolder.mkdir(); // 创建拼接文件夹 copyFolder(file,destZiFolder); // 递归 }else { String srcFileName = file.getName(); // 获取该文件名 File destFile = new File(destFolder, srcFileName); // 拼接 copyFile(file,destFile); } } } // 复制全部文件 public static void copyFile(File srcFile,File destFile) throws IOException { BufferedInputStream bis = new BufferedInputStream(new FileInputStream(srcFile)); BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(destFile)); // 缓冲流一次读写一个字节数组 int len; byte[] bytes = new byte[8192]; // 字符数组 while ((len = bis.read(bytes)) != -1){ // 读 bos.write(bytes,0,len); // 写 } bis.close(); bos.close(); } }
运行代码后,全部文件将会被复制到 day10\iofile 文件夹下:
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)