1. 程式人生 > 實用技巧 >簡單實現複製整個目錄(原始碼)

簡單實現複製整個目錄(原始碼)

複製整個目錄(原始碼)

關鍵字:FileFileInputStreamFileOutputStream

public class CopyDirectorys {

    /**
     * 以遞迴的方式拷貝整個目錄
     * @param copyPath 需要拷貝的目錄路徑
     * @param newPath 新的目錄
     * @throws Exception
     */
    public static void copy(String copyPath, String newPath) throws Exception {
        File file = new File(copyPath);
        File file1 = new File(newPath);
        if (!file.isDirectory() || !file1.isDirectory()) {
            // 自定義錯誤
            throw new FileIsNotDirectoryException("傳入引數不是目錄路徑");
        }

        // 轉為 絕對路徑
        copyPath = file.getAbsolutePath();
        newPath = file1.getAbsolutePath();

        // 在新路徑下建立目錄 並返回新路徑+檔名
        newPath = mkdir(newPath, file.getName());

        File[] files = file.listFiles();
        // 目錄沒有檔案就返回
        if (files == null || files.length == 0) {
            return;
        }
        // 檔名
        String filename = "";
        for (File f : files) {
            filename = f.getName();
            if (f.isDirectory()) {
                // 是目錄 就 遞迴拷貝
                copy(copyPath + "\\" + filename, newPath);
            } else {
                // 不是目錄 就 複製檔案
                copyFile(copyPath + "\\" + filename, newPath + "\\" + filename);
            }
        }
    }

    /**
     * 新建目錄並返回新的路徑
     *
     * @param path 需要新增目錄的路徑
     * @param name 目錄名
     * @return 新的路徑 原路徑+目錄名
     */
    private static String mkdir(String path, String name) {
        String newPath = path + "\\" + name;
        new File(newPath).mkdir();
        return newPath;
    }

    /**
     * 複製檔案
     *
     * @param inputPath  需要複製的檔案的路徑
     * @param outputPath 寫入檔案的路徑
     * @throws IOException
     */
    private static void copyFile(String inputPath, String outputPath) throws IOException {
        FileInputStream fis = new FileInputStream(inputPath);
        FileOutputStream fos = new FileOutputStream(outputPath);

        byte[] bytes = new byte[1024 * 1024];
        int count = 0;
        while ((count = fis.read(bytes)) != -1) {
            fos.write(bytes, 0, count);
        }

        fis.close();
        fos.flush();
        fos.close();
    }
}