【复制多级文件夹(复制指定目录下的内容到另一指定目录下)】

时间:2022-12-25 12:34:01
package com.yjf.esupplier.common.test;

import java.io.*;

/**
 * @author shusheng
 * @description
 * @Email shusheng@yiji.com
 * @date 2018/12/8 14:34
 */
public class CopyFolderDemo {

    public static void main(String[] args) throws IOException {

        File srcFile = new File("D:\\JZ-FILES\\jhcc\\templet-assemble");
        File destFile = new File("D:\\test");
        if(!destFile.exists()){
            destFile.mkdir();
        }

        copyFolder(srcFile,destFile);
    }

    private static void copyFolder(File srcFile, File destFile) throws IOException {
        if(srcFile.isDirectory()){
            File newFolder = new File(destFile,srcFile.getName());
            newFolder.mkdir();

            File[] fileArray = srcFile.listFiles();
            for(File file:fileArray){
                copyFolder(file,newFolder);
            }
        }else{
            File newFile = new File(destFile,srcFile.getName());
            copyFile(srcFile,newFile);
        }
    }

    private static void copyFile(File srcFile, File newFile) throws IOException {
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream(srcFile));
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(newFile));

        byte[] bys = new byte[1024];
        int len=0;
        while((len=bis.read(bys))!=-1){
            bos.write(bys);
        }
        bis.close();
        bos.close();
    }

}