基础_多线程文件拷贝

来源:互联网 发布:汽车管家软件 编辑:程序博客网 时间:2024/06/08 02:16

基本思路:对于多线程拷贝需要实现的就是两个功能点
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();;        }    }}
原创粉丝点击