Java递归复制多级目录及文件

本文介绍了一个使用Java实现的多级文件夹复制程序。该程序通过递归方式判断源文件夹下的每个条目是否为文件夹或文件,并相应地在目标位置创建或复制。程序利用了字节流进行文件内容的高效传输。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
/*
 * 需求:复制多级文件夹
 * 
 * 数据源:D:\\1
 * 目的地:F:\\新建文件夹
 * 
 * 分析:
 *      A:封装数据源File
 *      B:封装目的地File
 *      C:判断该File是文件夹还是文件
 *          a:是文件夹
 *              就在目的地目录下创建该文件夹
 *              获取该File对象下的所有文件或者文件夹File对象
 *              遍历得到每一个File对象
 *              回到C
 *          b:是文件
 *              就复制(字节流)
 */


public class C1 {
public static void main(String[] args) throws IOException {
    File srcFolder = new File("D:\\1");
    File dstFolder = new File("F:\\新建文件夹");
    judge(srcFolder,dstFolder);
}

private static void judge(File srcFolder,File dstFolder) throws IOException {
    if(srcFolder.isDirectory()){
        File newFolder = new File(dstFolder,srcFolder.getName());
        newFolder.mkdir();

        File[] fileArr = srcFolder.listFiles();
        for(File f:fileArr){
            judge(f, newFolder);

        }
    }else{
        File newFile = new File(dstFolder,srcFolder.getName());
//      System.out.println(newFile);
        copyFile(srcFolder,newFile);

    }

}

private static void copyFile(File srcFolder, File newFile) throws IOException {
    // TODO Auto-generated method stub

    BufferedInputStream bis = new BufferedInputStream(new FileInputStream(
            srcFolder));
    BufferedOutputStream bos = new BufferedOutputStream(
            new FileOutputStream(newFile));

    byte[] bys = new byte[1024];
    int len = 0;
    while ((len = bis.read(bys)) != -1) {
        bos.write(bys, 0, len);

    }

    bos.close();
    bis.close();
}


}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值