多线程递归拷贝多层目录文件

本文展示了如何使用Java进行多线程处理,递归地复制包括多层子目录在内的整个文件结构。通过这段代码,可以高效地进行大量文件的迁移或备份操作。

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

废话不多说,直接看代码!
 

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
//多线程多层目录文件拷贝
public class Thread3 extends Thread {
    private String str;//源地址
    private String dstr;//目的地址
    public Thread3(String str, String dstr){
        this.str = str;
        this.dstr = dstr;
        this.start();//启动线程
        try {
            this.sleep(1000);
        } catch (Exception e) {
// TODO: handle exception
            e.printStackTrace();
        }
    }
    @Override
    public void run(){
        File s = new File(str); //创建源文件
        File ds = new File(dstr);//创建源文件
        if(s.isDirectory()){//判断源文件是否为目录;
            if(!ds.exists()){//判断目的目录是否存在
                ds.mkdir(); //如果目的目录不存在,则创建目的目录
            }
            String [] spath = s.list();//取出源目录下的所有子目录;
            for(String sptr:spath){//遍历所有子目录,进行递归实现
                File es = new File(s,sptr); //创建源文件
                File des = new File(ds,sptr);//创建源文件
                Thread3 t = new Thread3(es.getAbsolutePath(),des.getAbsolutePath());//增加另一个拷贝线程
            }
        }else{//源文件不是目录,则直接进行拷贝
            System.out.println(Thread.currentThread().getName()+s.getAbsolutePath()+"开始拷贝");
            copy(s,ds);//拷贝源文件到目的文件ds中
        }
    }
    public void copy(File s,File d){ //文件拷贝
        InputStream fis = null; //文件输入流声明
        OutputStream fos = null;//文件输出流声明
        try {
            fis = new FileInputStream(s); 
            fos = new FileOutputStream(d);
            int n = -1;
            byte [] buffer = new byte[1024*1024];
            while((n = fis.read(buffer)) != -1){
                fos.write(buffer, 0, n);
            }
        } catch (Exception e) {
// TODO: handle exception
            e.printStackTrace();
        }finally{
            try {
                fos.flush();
                fos.close();
                fis.close();
                System.out.println(Thread.currentThread().getName()+s.getAbsolutePath()+"结束拷贝");
            } catch (Exception e2) {
// TODO: handle exception
                e2.printStackTrace();
            }
        }
    }





}

public class Test3 {
    public static void main(String[] args){
        Thread3 t = new Thread3("H:\\aa","H:\\fek");
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值