首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

Java 實作 xCopy 目錄遞歸複製工具:支援大檔案流式複製與錯誤處理

     編輯:Java 相關知識

模擬 Windows xcopy 指令,使用 Java 遞歸遍歷目錄、建立子目錄、流式複製檔案內容,包含權限檢查、例外處理與耗時統計功能。

核心類別:FileSystem

  • listFiles(String path):遞歸列印目錄結構,區分目錄 (D--) 與檔案 (F--),收集檔案絕對路徑至 fileList。
  • xCopy(String srcDir, String destDir):遞歸複製整個目錄樹,來源/目標目錄必須存在。
  • copyFile(String src, String dest):1024 bytes 緩衝區流式複製單一檔案。

關鍵實作細節

// xCopy 遞歸邏輯
File[] files = srcDir.listFiles();
for (File f : files) {
  if (f.isDirectory()) {
    String subSrc = srcDir.getPath() + File.separator + f.getName();
    String subDest = destDir.getPath() + File.separator + f.getName();
    new File(subDest).mkdir(); // 建立對應子目錄
    xCopy(subSrc, subDest);    // 遞歸處理
  } else {
    copyFile(f.getAbsolutePath(), destDir + File.separator + f.getName());
  }
}

// copyFile 流式複製
byte[] buffer = new byte[1024];
int byteread;
while ((byteread = in.read(buffer)) != -1) {
  out.write(buffer, 0, byteread);
}

錯誤處理與健壯性

  • checkDir(File):驗證目錄非 null、存在、可讀、確為目錄。
  • SecurityException 捕獲:無權限列舉目錄或建立目錄時中斷並列印堆疊。
  • 資源關閉放在 finally 區塊確保釋放。

執行方式

public static void main(String[] args) {
  if (args.length == 1) new FileSystem(args[0]);
  else new FileSystem(System.getProperty("user.dir", "c:\\"));
}

輸出範例:TimeCost: 1234 Millis 顯示掃描耗時。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved