多线程拷贝文件

来源:互联网 发布:做菜单用什么软件 编辑:程序博客网 时间:2024/06/08 18:19

多线程拷贝文件的步骤:
声明一个带有(源文件,目标文件,当前线程拷贝开始位置,当前线程拷贝结束位置)这4个参数的构造器
拷贝线程中需要实现:
1.统计当前线程的拷贝进度;
2.使用RandomAccessFile获取输出流,然后使用seek()方法跳过需要读写字节数;
3.while循环的条件要加上当前线程的拷贝进度小于等于(结束位置-开始位置),每次读写时,当前线程拷贝进度都要加上读取长度len;
主方法中将文件平均分为4段,使用for循环创建4个线程.
这里写图片描述

public class ThreadFileCopy extends Thread {    private File source;// 源文件    private File target;// 目标文件    private long start;// 当前线程拷贝开始位置    private long end;// 当前线程拷贝结束位置    public ThreadFileCopy(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 (FileNotFoundException e) {            e.printStackTrace();        } catch (IOException e) {            e.printStackTrace();        }finally{            try {                if(output != null)output.close();                if(input != null)input.close();            } catch (IOException e) {                e.printStackTrace();            }        }    }    public static void main(String[] args) {        File source = new File("D:\\工具\\eclipse-32-64");        File target = new File("C:\\Users\\94297\\Desktop",                source.getName());        // 将文件平均分为4段        long item = source.length() / 4;// 每一段长度        for (int i = 0; i < 4; i++) {            new ThreadFileCopy(source, target, i * item, (i + 1) * item).start();        }    }}
原创粉丝点击