JAVA : 通过多线程和高效流实现一个文件夹下多个大型文件的快速复制

1.使用IO流的高效率创建文件复制方法

2.遍历文件夹下的多个文件,为每一个文件创建一个线程

3.开启创建的多个线程

相关代码如下:

创建线程类

package demo1;
import java.io.*;
public class ThreadFileCopy extends Thread {
//    在类中传入数据,通过构造方法
    private String newaddress;
    private File f;

    public ThreadFileCopy(String newaddress, File f) {
        this.newaddress = newaddress;
        this.f = f;
    }
    public void run()  {
        if (!f.exists()) {
            System.out.println("找不到文件");

        }
        File newfile = new File(newaddress);
        if (!newfile.exists()) {
            newfile.mkdirs();
        }
        FileInputStream in = null;
        try {
            in = new FileInputStream(f);
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        }
//        创建高效输入流
        BufferedInputStream bufferin  = new BufferedInputStream(in);
        File file = new File(newfile, f.getName());
        FileOutputStream out = null;
        try {
            out = new FileOutputStream(file);
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        }
        BufferedOutputStream bufferout = new BufferedOutputStream(out);
        int length;
        byte[] bytes = new byte[1024];
        while (true){
            try {
                if (!((length=bufferin.read(bytes))!=-1)) break;
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            try {
                bufferout.write(bytes,0,length);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }

        }
        try {
            bufferin.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        try {
            bufferout.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }


}

测试代码:

package demo1;

import java.io.File;

public class Test2 {
    public static void main(String[] args) {
        File file = new File("e:/视频");
        File[] files = file.listFiles();
        for (File file1 : files) {
            ThreadFileCopy t1 = new ThreadFileCopy("e:/视频副本",file1);
            t1.start();
        }
    }
}

  • 8
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值