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");
}