1. 程式人生 > 實用技巧 >Java 目錄拷貝

Java 目錄拷貝

目錄拷貝

  1、首先是原始檔和拷貝目標目錄

  2、確定遞迴方法的邏輯,終止條件:是檔案時終止

  3、當是目錄時,建立目錄,當是檔案時拷貝檔案

  

  

package com.bjpowernode.java.io;

import java.io.*;

/*
拷貝目錄
 */
public class CopyAll {
    public static void main(String[] args) {
        // 拷貝源
        File srcFile = new File("D:\\course\\02-JavaSE\\document");
        
// 拷貝目標 File destFile = new File("C:\\a\\b\\c"); // 呼叫方法拷貝 copyDir(srcFile, destFile); } /** * 拷貝目錄 * @param srcFile 拷貝源 * @param destFile 拷貝目標 */ private static void copyDir(File srcFile, File destFile) { if(srcFile.isFile()) {
// srcFile如果是一個檔案的話,遞迴結束。 // 是檔案的時候需要拷貝。 // ....一邊讀一邊寫。 FileInputStream in = null; FileOutputStream out = null; try { // 讀這個檔案 // D:\course\02-JavaSE\document\JavaSE進階講義\JavaSE進階-01-面向物件.pdf in = new FileInputStream(srcFile);
// 寫到這個檔案中 // C:\course\02-JavaSE\document\JavaSE進階講義\JavaSE進階-01-面向物件.pdf String path = (destFile.getAbsolutePath().endsWith("\\") ? destFile.getAbsolutePath() : destFile.getAbsolutePath() + "\\") + srcFile.getAbsolutePath().substring(3); out = new FileOutputStream(path); // 一邊讀一邊寫 byte[] bytes = new byte[1024 * 1024]; // 一次複製1MB int readCount = 0; while((readCount = in.read(bytes)) != -1){ out.write(bytes, 0, readCount); } out.flush(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if (out != null) { try { out.close(); } catch (IOException e) { e.printStackTrace(); } } if (in != null) { try { in.close(); } catch (IOException e) { e.printStackTrace(); } } } return; } // 獲取源下面的子目錄 File[] files = srcFile.listFiles(); for(File file : files){ // 獲取所有檔案的(包括目錄和檔案)絕對路徑 //System.out.println(file.getAbsolutePath()); if(file.isDirectory()){ // 新建對應的目錄 //System.out.println(file.getAbsolutePath()); //D:\course\02-JavaSE\document\JavaSE進階講義 源目錄 //C:\course\02-JavaSE\document\JavaSE進階講義 目標目錄 String srcDir = file.getAbsolutePath(); String destDir = (destFile.getAbsolutePath().endsWith("\\") ? destFile.getAbsolutePath() : destFile.getAbsolutePath() + "\\") + srcDir.substring(3); File newFile = new File(destDir); if(!newFile.exists()){ newFile.mkdirs(); } } // 遞迴呼叫 copyDir(file, destFile); } } }