A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

一、多线程复制文件

思路:

用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();
        }
    }
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
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();
        }
    }

}

---------------------
【转载,仅作分享,侵删】
作者:初心魏
原文:https://blog.csdn.net/qq_42306803/article/details/86603401


1 个回复

倒序浏览
奈斯
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马