java-通过IO流复制文件夹到指定目录

本文提供了一个使用Java实现文件夹及其内容复制的例子。通过递归遍历源文件夹中的所有文件和子文件夹,并将它们复制到目标位置。利用BufferedInputStream和BufferedOutputStream进行高效的文件读写。

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

java-通过IO流复制文件夹到指定目录

 
public class copyDirectoryDemo {

    public static void main(String[] args) {
        File srcFolder = new File("C:\\Users\\MA\\Desktop\\IOtest");
        File destFolder = new File("C:\\Users\\MA\\Desktop\\IOtest\\test");
        fun(srcFolder, destFolder);
    }

    public static void fun(File srcFolder, File destFolder) {
        File[] fileArray = srcFolder.listFiles();
        if (!destFolder.exists()) {
            destFolder.mkdir();
        }
        for (File file : fileArray) {
            if (file.isDirectory()) {
                String folderName = file.getName();
                File newDestFolder = new File(destFolder, folderName);
                fun(file, newDestFolder);
            } else {
                String fileName = file.getName();
                File destFile = new File(destFolder, fileName);
                copy(file, destFile);
            }
        }
    }

    public static void copy(File file, File destFile) {
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        try {
            bis = new BufferedInputStream(new FileInputStream(file));
            bos = new BufferedOutputStream(new FileOutputStream(destFile));
            byte[] bys = new byte[1024];
            int len = 0;
            while((len=bis.read(bys))!=-1){
                bos.write(bys,0,len);
                
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }catch (IOException e){
            e.printStackTrace();
        }finally{
            if(bis!=null){
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(bos!=null){
                try {
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            
        }    
    }
}

 

 

 
 
 
 
 
 
 
posted @ 2018-07-22 00:39 M_x_j 阅读(...) 评论(...) 编辑 收藏
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值