Java实现文件夹的复制,包含子文件夹

定义方法实现文件夹的复制

把源文件夹中所有的内容复制到目标文件夹中,

先判断目标文件夹是否存在,如果目标文件夹不存在则先创建目标文件夹

遍历源文件夹的内容

    如果是文件则直接复制到目标文件夹中

    如果是文件夹,则把子文件夹也复制到目标文件夹中(递归调用)

public class Test01 {
    public static void main(String[] args) {
        String srcFolder="D:/bj2003"; //源文件夹
        String destFolder="D:/tmp";  //目标文件夹
        //定义方法实现文件夹复制
        copyFolder(srcFolder,destFolder);
    }

    private static void copyFolder(String srcFolder, String destFolder) {
        //判断源文件夹是否存在
        File srcDir=new File(srcFolder);
        if (!srcDir.exists()){
            System.out.println("源文件夹不存在");
            return;
        }

        //判断目标文件夹是否存在,不存在则创建
        File destDir=new File(destFolder);
        if (!destDir.exists()){
            destDir.mkdirs();
        }

        //遍历源文件夹的内容
        File[] files = srcDir.listFiles();
        for (File file : files) {
            //file不管是文件还是文件夹,在目标文件夹和源文件夹中的名字都相同,只是存储路径不同,先构建目标文件对象
            File destFile=new File(destDir,file.getName());
            if (file.isFile()){
                //如果file是文件就执行复制文件的方法
                copyFile(file,destFile);
            }else {
                //如果file是文件夹,就递归调用复制文件夹的方法
                copyFolder(file.getAbsolutePath(), destFile.getAbsolutePath());
            }
        }
    }

    //定义方法实现文件的复制
    private static void copyFile(File srcFile,File destFile){
        try(FileInputStream fis=new FileInputStream(srcFile);
            FileOutputStream fos=new FileOutputStream(destFile);) {
            byte[] bytes=new byte[1024];
            int len=fis.read(bytes);
            while (len!=-1){
                fos.write(bytes, 0, len);
                len=fis.read(bytes);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}

 


版权声明:本文为qq_40846913原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。