java多线程复制文件,RandomAccessFile类

package com.wzh.mtd.t20151102;

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

public class CopyThread implements Runnable{

	private int block;
	private int blockNum;
	private String startFile;
	private String endFile;
	
	public CopyThread(int block,int blockNum,String startFile,String endFile){
		this.block = block;
		this.block = blockNum;
		this.startFile = startFile;
		this.endFile = endFile;
	}
	
	@Override
	public void run() {
		try {
			RandomAccessFile ra =  new RandomAccessFile(startFile,"r");
			RandomAccessFile ra2 =  new RandomAccessFile(endFile,"rw");
			
			//源文件大小
			long size = ra.length();
			//每一块的大小
			long blockSize = size / block;
			//开始的位置
			long startPos = blockNum * blockSize;
			
			int curRedLength ;
			long allRedLength = 0;
			
			//缓冲区
			byte[] buff = new byte[1024*1024];
			//跳到需要读取的位置
			ra.seek(startPos);
			ra2.seek(startPos);
			
			while( (curRedLength = ra.read(buff))!=-1 && allRedLength<blockSize  ){
				ra2.write(buff,0,curRedLength);
				allRedLength+=curRedLength;
			}
			
			ra.close();ra2.close();
			
			
			
			
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}catch(IOException e){
			e.printStackTrace();
		}
	
		
	}

}


@Test
	public void testSecond() throws InterruptedException{
		long start = System.currentTimeMillis();
		Thread t1  = new Thread(new CopyThread(5, 1, "resource/a.zip", "resource/b.zip"));
		Thread t2  = new Thread(new CopyThread(5, 2, "resource/a.zip", "resource/b.zip"));
		Thread t3  = new Thread(new CopyThread(5, 3, "resource/a.zip", "resource/b.zip"));
		Thread t4  = new Thread(new CopyThread(5, 4, "resource/a.zip", "resource/b.zip"));

		
		t1.start();t2.start();t3.start();t4.start();t1.join();t2.join();t3.join();t4.join();
		long end = System.currentTimeMillis();
		System.out.println((end - start)/1000+"S");
		
	}
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值