java拷貝目錄及其子目錄、檔案,到另外一個目錄
阿新 • • 發佈:2019-02-07
/** * 複製一個目錄及其子目錄、檔案到另外一個目錄 * @param src * @param dest * @throws IOException */ private void copyFolder(File src, File dest) throws IOException { if (src.isDirectory()) { if (!dest.exists()) { dest.mkdir(); } String files[] = src.list(); for (String file : files) { File srcFile = new File(src, file); File destFile = new File(dest, file); // 遞迴複製 copyFolder(srcFile, destFile); } } else { InputStream in = new FileInputStream(src); OutputStream out = new FileOutputStream(dest); byte[] buffer = new byte[1024]; int length; while ((length = in.read(buffer)) > 0) { out.write(buffer, 0, length); } in.close(); out.close(); } }
PS: apache commons-io包,FileUtils有相關的方法,IOUtils一般是拷貝檔案。
刪除目錄結構 FileUtils.deleteDirectory(dest);
遞迴複製目錄及檔案 FileUtils.copyDirectory(src, dest);