java入门篇(26)多线程复制文件

一、多线程复制文件

思路:

  • 用n个线程复制文件,将文件file等分成每个大小为file.length()/n的小份文件。
  • 得到每一份的文件的"首指针"和"尾指针"
  • 用随机文件流RandomAccessFile进行读写
  • 控制读写时"首指针"的范围
  • 原文件剩余的部分再开启新的线程进行处理
public class thread_file_copy {
    public static void main(String[] args) throws FileNotFoundException {
        String src = "D:\\java\\01_JAVA SE基础\\01 变量与数据类型\\视频\\avi\\01.13_变量的概述和定义格式.avi";
        String des = "D:\\01.13_变量的概述和定义格式.avi";
        File file = new File(src);
        long len = file.length();
        long start = 0, end = 0;
        long threadnum = 5;
        for(long i = 0; i < threadnum; i++) {
           start = i*len/5;
           end = (i+1)*len/5;
           new file_copy(start, end, src,des).start();
        }
        long last = len % threadnum;
        if(last != 0) {
            start = end + 1;
            end = len;
            new file_copy(start, end, src, des).start();
        }
    }
}

public class file_copy extends Thread {
    long start;
    long end;
    RandomAccessFile in = null;
    RandomAccessFile out = null;
    public file_copy(long start, long end, String src, String des) throws FileNotFoundException {
        this.start = start;
        this.end = end;
        in = new RandomAccessFile(src, "rw");
        out = new RandomAccessFile(des, "rw");
    }
    @Override
    public void run() {
        try {
            in.seek(start);
            out.seek(start);
            byte[] bytes = new byte[1024];
            int len = in.read(bytes);
            while((len = in.read(bytes)) != -1) {
                out.write(bytes, 0, len);
                start = start + len;
            }
            in.close();
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值