IO流實現檔案的拷貝
阿新 • • 發佈:2020-12-17
public class Demo1 { public static void main(String[] args) { //裁剪的檔案 String f1 = "C:\\Users\\KAlways18\\Desktop\\1216作業\\1216作業"; //儲存的位置 String f2 = "C:\\Users\\KAlways18\\Desktop\\1216作業\\第一題完成後沒有這個資料夾\\1216作業\\1216作業1"; One(f1, f2); } //先進行檔案的父目錄的建立在進行子目錄的建立 public static void One(String f1, String f2) { File crop = new File(f1); File save = new File(f2, crop.getName()); if (!save.exists()) {//判斷目錄是否存在 save.mkdir(); } traverse(crop.getAbsolutePath(), save.getAbsolutePath());//呼叫方法 } //穿過 public static void traverse(String f1, String f2) { try { File crop = new File(f1);//拷貝 if (!crop.isDirectory()) {//如果不是檔案就不復制 return; } File save = new File(f2);//儲存 if (!save.exists()) {//判斷路徑是否存在不存在就建立 save.mkdir(); } File[] files = crop.listFiles(); for (File f : files) { //separator與系統相關的預設分隔符 String strCrop = f1 + File.separator + f.getName();//拼接 System.out.println("需要複製資料夾:" + strCrop); String strSave = f2 + File.separator + f.getName(); System.out.println("貼上資料夾:" + strSave); if (f.isDirectory()) { System.out.println("\n正在建立資料夾" + f.getName() + "\n"); traverse(strCrop, strSave); } //如果是檔案就進行寫入 if (f.isFile()) { System.out.println("\n正在建立檔案" + f.getName() + "\n"); makeFile(strCrop, strSave); } } } catch (Exception e) { System.out.println("檔案可能找不到"); e.printStackTrace(); } } //檔案複製 public static void makeFile(String f1, String f2) { try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream(f1));//輸入讀取 BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(f2));//輸出寫入 ) { int tem = 0; byte[] b = new byte[1024]; while ((tem = bis.read(b)) != -1) { bos.write(b); } } catch (IOException e) { e.printStackTrace(); } } }