Java使用遞歸復(fù)制文件夾及文件夾
遞歸調(diào)用copyDir方法實現(xiàn),查詢源文件目錄使用字節(jié)輸入流寫入字節(jié)數(shù)組,如果目標文件目錄沒有就創(chuàng)建目錄,如果迭代出是文件夾使用字節(jié)輸出流對拷文件,直至源文件目錄沒有內(nèi)容。
/** * 復(fù)制文件夾 * @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; //創(chuàng)建目標文件夾 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);} } } }
/** * 復(fù)制文件夾 * * @param path 路徑 * @param destDir 目錄 */ public static void copyFile(String path, String destDir) { FileInputStream fis = null; FileOutputStream fos = null; try { /*準備目錄取出相對的路徑創(chuàng)建目標文件所在的文件目錄 */ 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); //創(chuàng)建文件輸入流 fis = new FileInputStream(path); //定義新路徑 //創(chuàng)建文件 輸出流 fos = new FileOutputStream(new File(destFolder,new File(path).getName())); //創(chuàng)建字節(jié)數(shù)組進行流對拷 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(); } } }
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. XML入門的常見問題(三)2. HTTP協(xié)議常用的請求頭和響應(yīng)頭響應(yīng)詳解說明(學(xué)習(xí))3. ASP基礎(chǔ)入門第四篇(腳本變量、函數(shù)、過程和條件語句)4. HTML5實戰(zhàn)與剖析之觸摸事件(touchstart、touchmove和touchend)5. .NET Framework各版本(.NET2.0 3.0 3.5 4.0)區(qū)別6. ASP將數(shù)字轉(zhuǎn)中文數(shù)字(大寫金額)的函數(shù)7. XML在語音合成中的應(yīng)用8. jscript與vbscript 操作XML元素屬性的代碼9. php使用正則驗證密碼字段的復(fù)雜強度原理詳細講解 原創(chuàng)10. 不要在HTML中濫用div
