国产成人精品亚洲777人妖,欧美日韩精品一区视频,最新亚洲国产,国产乱码精品一区二区亚洲

您的位置:首頁技術文章
文章詳情頁

Java使用遞歸復制文件夾及文件夾

瀏覽:2日期:2022-09-01 16:23:14

遞歸調用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(); } } }

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持好吧啦網。

標簽: Java
相關文章:
主站蜘蛛池模板: 资阳市| 麻阳| 曲靖市| 河北区| 宁都县| 双流县| 金寨县| 长兴县| 永平县| 石台县| 大冶市| 积石山| 许昌县| 南投市| 通州区| 大同县| 永康市| 新巴尔虎右旗| 上高县| 逊克县| 临邑县| 宁海县| 富蕴县| 巴青县| 阳新县| 阿合奇县| 元阳县| 论坛| 甘洛县| 汉沽区| 合肥市| 厦门市| 南召县| 绥阳县| 百色市| 博客| 页游| 南部县| 贡觉县| 岳阳县| 扎鲁特旗|