java 複製資料夾
阿新 • • 發佈:2019-01-09
package Copy; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; /* * 複製一個資料夾到另一個檔案下 */ public class Copy { public static void main(String[] args) throws IOException { File src = new File("E:\\考試程式碼"); File dest = new File("D:\\"); copyFolder(src, dest); System.out.println("OK"); } static void copyFolder(File src, File dest) { if (src.isDirectory()) { // 如果目標目錄不存在則建立 if (!dest.exists()) { dest.mkdirs(); } // 獲取此目錄下的檔案及目錄的名字 String files[] = src.list(); for (String file : files) { System.out.println(file); // 根據(src,dest)父抽象路徑名和子路徑名字串(file)建立一個新的例項 File srcFile = new File(src, file); File destFile = new File(dest, file); // 遞迴複製檔案 copyFolder(srcFile, destFile); } } else { // 如果是檔案則直接複製 FileInputStream fis = null; FileOutputStream fos = null; try { // 建立輸入流,讀取檔案 fis = new FileInputStream(src); // 建立輸出流,寫入檔案 fos = new FileOutputStream(dest); byte[] bs = new byte[1024]; int count; while ((count = fis.read(bs)) != -1) { fos.write(bs, 0, count); fos.flush(); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally {// 關流釋放資源 if (fos != null) { try { fos.close(); } catch (IOException e) { e.printStackTrace(); } } if (fis != null) { try { fis.close(); } catch (IOException e) { e.printStackTrace(); } } } } } }