基础_多线程文件拷贝

基本思路:对于多线程拷贝需要实现的就是两个功能点
1、求出文件的长度。
2、计算每一个线程的起始位置和结束位置。

public class ThreadCopy extends Thread {
    private File source;// 源文件
    private File target;// 目标文件
    private long start;// 拷贝的起始位置
    private long end;// 拷贝的结束位置

    public ThreadCopy(File source, File target, long start, long end) {
        super();
        this.source = source;
        this.target = target;
        this.start = start;
        this.end = end;
    }

    @Override
    public void run() {
        System.out.println(this.getName() + "开始拷贝");
        int count = 0;// 统计当前线程拷贝长度
        RandomAccessFile input = null;
        RandomAccessFile output = null;
        try {
            // 从源文件中读取内容输入到目标文件当中,输入流用于读取文件
            input = new RandomAccessFile(source, "r");
            // 输出流用于将程序中的内容输出到文件当中
            output = new RandomAccessFile(target, "rw");
            // 使用多线程拷贝是后面的线程需要跳过一段,输入与输出的位置应该是一样的
            input.seek(start);
            output.seek(start);
            byte[] b = new byte[1024];
            int len = 0;
            while (((len = input.read(b)) != -1) && count < (end - start)) {
                count += len;
                output.write(b, 0, len);
            }
            System.out.println(this.getName()+"拷贝结束:"+count);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
public class MainCopy {

    public static void main(String[] args) {
        File source = new File("C:\\Users\\RisingSun\\Videos\\Captures\\1.mp4");
        File target = new File("C:\\Users\\RisingSun\\Desktop", source.getName());
        // 获取源文件的长度
        long length = source.length();
        // 将文件分为三个线程来拷贝
        long item = length / 3;
        //创建三个线程,在开始拷贝前就已经计算好了开始拷贝位置以及结束位置
        for (int i = 0; i < 3; i++) {
            new ThreadCopy(source, target, i * item, (i + 1) * item).start();;
        }

    }
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值