使用RandomAccessFile类采用多线程方式完成文件复制

使用RandomAccessFile类采用多线程方式完成文件复制

最近遇到了一个基础类,RandomAccessFile类。学习了一下其使用方法,记录下来。

一、定义自己复制线程

public class CopyThread extends Thread {
    private RandomAccessFile rf;//提供文件读取的流
    private RandomAccessFile wf;//提供文件写入的流
    private long startPoint;    //标记文件copy的位置
    public final static int COPY_SIZE=10;//每一个线程负责复制的文件大小为10*1024,差不多10kb
    //初始化文件读,写,复制位置
    public CopyThread(File fr, File fw, long startPoint) {
        try {
            this.rf = new RandomAccessFile(fr, "r");
            this.wf = new RandomAccessFile(fw, "rw");
        } catch (Exception e) {
            e.printStackTrace();
        }
        this.startPoint = startPoint;
    }
    @Override
    public void run() {
        try {
            //文件复制的常规操作
            rf.seek(startPoint);
            wf.seek(startPoint);
            byte[] buffer = new byte[1024];
            int len = 0;
            int maxSize = 0;
            while ((len = rf.read(buffer)) != -1&&maxSize<COPY_SIZE) {
                wf.write(buffer, 0, len);
                maxSize++;//标记复制的位置,达到10*1024,该线程任务结束
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                rf.close();
                wf.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

二、主类,测试

public class TestMain {

    public static void main(String[] args) throws Exception {
        int COPY_SIZE = CopyThread.COPY_SIZE;
        File f1 = new File("d:" + File.separator + "test01.txt");//待复制的文件
        File f2 = new File("d:" + File.separator + "test02.txt");//copy的文件
        if (!f1.exists()) {
            System.out.println("文件不存在。");
            return;
        }
        long length = f1.length();
        int bord = (int) length / (COPY_SIZE * 1024);
        bord = (int) length % (COPY_SIZE * 1024) == 0 ? bord : bord + 1;//初始化需要线程的数量
        for (int i = 0; i < bord; i++) {
            new CopyThread(f1, f2, i * COPY_SIZE * 1024).start();//启动线程
        }
        Thread.sleep(3000);//为了让所有线程全部复制完毕
        System.out.println("复制完成");
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值