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


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

你可能感兴趣的:(java)