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

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

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

Draogn   2021-04-22 我要评论

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

/**
   * 复制文件夹
   * @param srcDir 源文件目录
   * @param destDir 目标文件目录
   */
  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);
        }
      }
    }
  }
/**
   * 复制文件夹
   *
   * @param path  路径
   * @param 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();
      }
    }
  }

猜您喜欢

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们