Java使用遞歸復(fù)制文件夾及文件夾
遞歸調(diào)用copyDir方法實(shí)現(xiàn),查詢?cè)次募夸浭褂米止?jié)輸入流寫入字節(jié)數(shù)組,如果目標(biāo)文件目錄沒有就創(chuàng)建目錄,如果迭代出是文件夾使用字節(jié)輸出流對(duì)拷文件,直至源文件目錄沒有內(nèi)容。
/** * 復(fù)制文件夾 * @param srcDir 源文件目錄 * @param destDir 目標(biāo)文件目錄 */ public static void copyDir(String srcDir, String destDir) { if (srcRoot == null) srcRoot = srcDir; //源文件夾 File srcFile = new File(srcDir); //目標(biāo)文件夾 File destFile = new File(destDir); //判斷srcFile有效性 if (srcFile == null || !srcFile.exists()) return; //創(chuàng)建目標(biāo)文件夾 if (!destFile.exists()) destFile.mkdirs(); //判斷是否是文件 if (srcFile.isFile()) { //源文件的絕對(duì)路徑 String absPath = srcFile.getAbsolutePath(); //取出上級(jí)目錄 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 { /*準(zhǔn)備目錄取出相對(duì)的路徑創(chuàng)建目標(biāo)文件所在的文件目錄 */ 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ù)組進(jìn)行流對(duì)拷 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(); } } }
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. ASP中if語句、select 、while循環(huán)的使用方法2. html小技巧之td,div標(biāo)簽里內(nèi)容不換行3. xml中的空格之完全解說4. ASP中解決“對(duì)象關(guān)閉時(shí),不允許操作?!钡脑幃悊栴}……5. XML入門的常見問題(四)6. php bugs代碼審計(jì)基礎(chǔ)詳解7. ASP使用MySQL數(shù)據(jù)庫(kù)的方法8. ASP動(dòng)態(tài)網(wǎng)頁制作技術(shù)經(jīng)驗(yàn)分享9. WMLScript的語法基礎(chǔ)10. msxml3.dll 錯(cuò)誤 800c0019 系統(tǒng)錯(cuò)誤:-2146697191解決方法
