栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Java使用递归复制文件夹及文件夹

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Java使用递归复制文件夹及文件夹

递归调用copyDir方法实现,查询源文件目录使用字节输入流写入字节数组,如果目标文件目录没有就创建目录,如果迭代出是文件夹使用字节输出流对拷文件,直至源文件目录没有内容。


  public static void copyDir(String srcDir, String destDir) {
    if (srcRoot == null) srcRoot = srcDir;
    //源文件夹
    File srcFile = new File(srcDir);
    //目标文件夹
    File destFile = new File(destDir);
    //判断srcFile有效性
    if (srcFile == null || !srcFile.exists())
      return;
    //创建目标文件夹
    if (!destFile.exists())
      destFile.mkdirs();
    //判断是否是文件
    if (srcFile.isFile()) {
      //源文件的绝对路径
      String absPath = srcFile.getAbsolutePath();
      //取出上级目录
      String parentDir = new File(srcRoot).getParent();
      //拷贝文件
      copyFile(srcFile.getAbsolutePath(), destDir);

    } else {  //如果是目录
      File[] children = srcFile.listFiles();
      if (children != null) {
 for (File f : children) {
   copyDir(f.getAbsolutePath(), destDir);
 }
      }
    }
  }

  public static void copyFile(String path, String destDir) {

    FileInputStream fis = null;
    FileOutputStream fos = null;
    try {

      String tmp = path.substring(srcRoot.length());
      String folder = new File(destDir, tmp).getParentFile().getAbsolutePath();
      File destFolder = new File(folder);
      destFolder.mkdirs();
      System.out.println(folder);      //创建文件输入流
      fis = new FileInputStream(path);
      //定义新路径
      //创建文件 输出流
      fos = new FileOutputStream(new File(destFolder,new File(path).getName()));
      //创建字节数组进行流对拷
      byte[] buf = new byte[1024];
      int len = 0;
      while ((len = fis.read(buf)) != -1) {
 fos.write(buf, 0, len);
      }
    } catch (IOException ex) {
      ex.printStackTrace();
    } finally {
      try {
 fis.close();
 fos.close();
      } catch (IOException e) {
 e.printStackTrace();
      }
    }
  }

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持考高分网。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/134096.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号