Java中递归复制多级文件夹(IO流)

需求:复制多级文件夹

代码演示:

import java.io.*;

public class CopyFolder {
    public static void main(String[] args) throws IOException {
        //封装源文件夹和目标文件夹
        File srcFolder = new File("F:\\SKT");
        File targetFolder = new File("F:\\" + srcFolder.getName() + "1");
        //若目标文件夹不存在,就创建出来
        if (!targetFolder.exists()){
            targetFolder.mkdirs();
        }
        //复制文件夹方法,参数1和参数2分别是源文件夹和目标文件夹
        copyFolder(srcFolder,targetFolder);
        System.out.println("复制完成!");
    }

    private static void copyFolder(File srcFolder, File targetFolder) throws IOException {
        //遍历源文件夹中的文件
        File[] files = srcFolder.listFiles();
        for (File file : files) {
            //如果是文件,就复制
            if (file.isFile()){
                copyFile(file,targetFolder);
            }else if (file.isDirectory()){
                //是文件夹就继续递归复制这个子文件夹
                File newFolder = new File(targetFolder,file.getName());
                if (!newFolder.exists()){
                    newFolder.mkdirs();
                }
                //递归这个子文件夹
                copyFolder(file,newFolder);
            }
        }
    }

    private static void copyFile(File file, File targetFolder) throws IOException {
        //封装目标文件夹中的文件
        File newFile = new File(targetFolder, file.getName());
        //使用字节流复制文件
        FileInputStream fis = new FileInputStream(file);
        FileOutputStream fos = new FileOutputStream(newFile);
        //一次读取一个字节数组
        int len = 0;
        byte[] bytes = new byte[1024 * 8];
        while ((len = fis.read(bytes)) != -1){
            fos.write(bytes,0,len);
        }
        fis.close();
        fos.close();
    }
}
发布了58 篇原创文章 · 获赞 7 · 访问量 2291

猜你喜欢

转载自blog.csdn.net/weixin_42492089/article/details/103162046