黑马程序员技术交流社区

标题: 【上海校区】java入门篇多线程复制文件 [打印本页]

作者: 不二晨    时间: 2019-1-26 09:45
标题: 【上海校区】java入门篇多线程复制文件
一、多线程复制文件

思路:

用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



作者: 不二晨    时间: 2019-2-14 14:50
奈斯




欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2