Java使用遞歸復(fù)制文件夾及文件夾
遞歸調(diào)用copyDir方法實現(xiàn),查詢源文件目錄使用字節(jié)輸入流寫入字節(jié)數(shù)組,如果目標(biāo)文件目錄沒有就創(chuàng)建目錄,如果迭代出是文件夾使用字節(jié)輸出流對拷文件,直至源文件目錄沒有內(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()) { //源文件的絕對路徑 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 { /* 準(zhǔn)備目錄 取出相對的路徑 創(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)行流對拷 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í)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
如何修改json字符串中某個key對應(yīng)的value值
這篇文章主要介紹了如何修改json字符串中某個key對應(yīng)的value值操作,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-11-11如何使用BeanUtils.copyProperties進(jìn)行對象之間的屬性賦值
這篇文章主要介紹了使用BeanUtils.copyProperties進(jìn)行對象之間的屬性賦值,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-05-05Java中保留兩位小數(shù)的四種方法實現(xiàn)實例
今天小編就為大家分享一篇關(guān)于Java中保留兩位小數(shù)的四種方法實現(xiàn)實例,小編覺得內(nèi)容挺不錯的,現(xiàn)在分享給大家,具有很好的參考價值,需要的朋友一起跟隨小編來看看吧2019-02-02Spring中的@CrossOrigin注解的使用詳細(xì)解讀
這篇文章主要介紹了Spring中的@CrossOrigin注解的使用詳細(xì)解讀,跨源資源共享(CORS),是由大多數(shù)瀏覽器實現(xiàn)的W3C規(guī)范,允許對跨域請求進(jìn)行靈活授權(quán),用來代替IFRAME或JSONP等非正規(guī)實現(xiàn)方式,需要的朋友可以參考下2023-11-11SpringMVC域?qū)ο蠊蚕頂?shù)據(jù)示例詳解
這篇文章主要為大家介紹了SpringMVC域?qū)ο蠊蚕頂?shù)據(jù)示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-05-05