java的IO流小作业,完成文件夹的拷贝,利用递归思想

import java.io.*;

public class Test {
    public static void main(String[] args) {
        //输入需要移动的文件夹,到哪个文件夹下的路径
        copyFolder("D:/测试", "c:/");
    }

    public static void copyFolder(String file, String dest) {
        //创建指定路径的文件对象
        File srcFile = new File(file);
        File destFile = new File(dest);

        copyFolder(srcFile, destFile);
    }

    public static void copyFolder(File srcFolder, File destFile) {

        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        try {
            File[] files = srcFolder.listFiles();

            //如果该文件不存在,则不执行
            if (files != null) {

                //在指定的文件夹下创建同名的文件夹
                File copyFolder = new File(destFile, srcFolder.getName());
                copyFolder.mkdir();

                //遍历该文件所有的第一级文件目录
                for (File file : files) {

                    //如果是文件
                    if (file.isFile()) {

                        //读取该文件
                        bis = new BufferedInputStream(new FileInputStream(file));

                        //在指定路径下创建同名的文件,并指定输出的内容输出到该文件
                        bos = new BufferedOutputStream(new FileOutputStream(new File(copyFolder, file.getName())));
                        int temp = 0;
                        while ((temp = bis.read()) != -1) {
                            bos.write(temp);
                        }

                        //如果不是文件
                    } else {
                        //递归,如果是文件夹则继续
                        copyFolder(file, copyFolder);
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {

            try {

                //关闭输入输出流
                if (bos != null) {
                    bos.close();
                }

                if (bis != null) {
                    bis.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

提桶跑

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值