1. 程式人生 > 程式設計 >Java使用遞迴複製資料夾及資料夾

Java使用遞迴複製資料夾及資料夾

遞迴呼叫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,len);
      }
    } catch (IOException ex) {
      ex.printStackTrace();
    } finally {
      try {
        fis.close();
        fos.close();
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
  }

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。