利用多线程和IO流进行文件复制

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;

public class OneThreadCopy {
    public static void main(String[] args) throws FileNotFoundException {
        //源文件
        File source=new File("f:/test/navicat150_premium_cs_x64.exe");
        //目标文件
        File destFile=new File("f:/test/navicat4.exe");
        //获取文件长度
        long length=source.length();
        //预计线程数
        long threadNum=3;
        //分割文件
        long average=length/threadNum;
        //创建多个线程
        for (int i = 0; i < threadNum; i++) {
            //0~100,101~200,201~300
            //开始位置
            long start=i*(average+1);
            //结束位置
            long end=(i+1)*average;
            //启动线程
            new Thread(new CopyThread(start,end,source,destFile)).start();
        }
        //有剩余在增加一个线程
        if(length%threadNum!=0) {
            new Thread(new CopyThread(average*threadNum+1, length, source, destFile)).start();
        }
    }
}
class CopyThread implements Runnable{
    private long start;
    private long end;
    public RandomAccessFile rsource=null;
    public RandomAccessFile rdestFile=null;
    public CopyThread(long start, long end, File source, File destFile) throws FileNotFoundException {
        this.start = start;
        this.end = end;
        this.rsource=new RandomAccessFile(source, "rw");
        this.rdestFile=new RandomAccessFile(destFile, "rw");
    }
    @Override
    public void run() {
        try {
            //光标移到初始位置
            rsource.seek(start);
            rdestFile.seek(start);
            //缓存区
            byte []bytes=new byte[1024*1024];
            //读取的个数
            int len=0;
            //源文件里光标的位置
            long point=rsource.getFilePointer();
            while(point<=end&&(len=rsource.read())!=-1) {
                //把长度为len的字节写入
                rdestFile.write(bytes,0,len);
                //光标移动len
                point+=len;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                rsource.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            try {
                rdestFile.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        
    }
    
}
 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值