使用JAVA递归复制多级文件夹

基本思想
用到递归,判断当前File对象是文件夹还是文件,如果是文件就直接复制;
如果是文件夹,就在目的地创建同名文件夹,再对文件夹下的File对象进行同样的判断和操作

分析
A:封装数据源、
B:封装目的地
C:判断该File是文件还是文件夹
	a:是文件夹
		就在目的地下创建该文件夹
		获取该File对象的所有文件或者文件夹对象
		历得到每一个File对象
		回到C
	b:是文件
		复制文件


    public static void main(String[] args) {
        //封装源文件
        File file = new File("C:\\Users\\DELL\\Desktop\\qqq");
        //封装目的地稳健
        File file1 = new File("D:\\Test9");
        //判断文件是否存在
        if(!file1.exists()){
            file1.mkdirs();
        }
        //复制文件夹
        //main方法里处理异常 最好不要再向JVM上抛
        try {
            CpFile(file,file1);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static void CpFile(File oldFile, File newFile) throws IOException {
        //判断是文件还是文件夹
        if(oldFile.isDirectory()){
            //是文件夹
            File f = new File(newFile, oldFile.getName());
            f.mkdirs();
            //遍历源文件夹
            File[] files = oldFile.listFiles();
            for (File file : files) {
                CpFile(file,f);
            }
        }else {
            //是文件直接复制
            File file = new File(newFile, oldFile.getName());
            copy(oldFile,file);
        }
    }

    private static void copy(File oldFile, File newFile) throws IOException {
        BufferedInputStream in = new BufferedInputStream(new FileInputStream(oldFile));
        BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(newFile));
        byte[] bytes = new byte[1024 * 8];
        int len = 0;
        while ((len=in.read(bytes))!=-1){
            out.write(bytes,0,len);
        }
        in.close();
        out.close();
    }
}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值