Java递归拷贝文件

package demo.io;

import java.io.*;

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

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

    //copy文件
    private static void copyFile(File file, File newFile) throws IOException {
        //读取源文件信息
        BufferedInputStream bufi = new BufferedInputStream(new FileInputStream(file));
        //写入新文件信息
        BufferedOutputStream 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();
        }
        bufi.close();
        bufo.close();
    }
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值