递归拷贝文件

package demo.io;

import java.io.*;

class 递归拷贝文件 {
    public static void main(String[] args) {
        File sourceDir = new File("I:\\Test\\2");//源
        File destDir = new File("I:\\Test\\22");//新目录
        listCopyAll(sourceDir, destDir);//递归拷贝文件
    }

    //递归拷贝文件                      sourceDir 源目录,destDir 新目录
    private static void listCopyAll(File sourceDir, File destDir) {
        destDir.mkdirs();//创建新目录
        File[] files = sourceDir.listFiles();//获取源目录文件对象列表
        for (File file : files) {//file源目录的最近一级子目录及文件
            if (file.isDirectory()) {//如果是目录就继续遍历
                //根据file传入new dir2子目录地址进行创建     listCopyAll中的两个参数同一水平
                listCopyAll(file, new File(destDir.getAbsolutePath(), file.getName()));//在自身目录上衔接目录
            } else {
                //拷贝文件 在自身目录上衔接文件
                copyFile(file, new File(destDir.getAbsolutePath(), file.getName()));
            }
        }
    }

    //copy文件
    private static void copyFile(File file, File newFile) {
        //读取源文件信息
        BufferedInputStream bufi = null;
        //写入新文件信息
        BufferedOutputStream bufo = null;
        try {
            bufi = new BufferedInputStream(new FileInputStream(file));
            bufo = new BufferedOutputStream(new FileOutputStream(newFile));//文件自动创建
            int len = 0;
            byte[] buf = new byte[1024];
            while ((len = bufi.read(buf)) != -1) {
                bufo.write(buf, 0, len);
                bufo.flush();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (bufi != null)
                    bufi.close();
                if (bufo != null)
                    bufo.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值