import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.RandomAccessFile; public class FileCope implements Runnable{ private String sourceFileName = null; //支援文件路径 private String targetFileName = null; //目标文件路径 private long blockCount; //总分块数 private long blockNo; //当前分块数 private int maxBufferSize = 1024; public FileCope(String sourceFileName, String targetFileName, long blockCount, long blockNo){ this.sourceFileName = sourceFileName; this.targetFileName = targetFileName; this.blockCount = blockCount; this.blockNo = blockNo; } public void run() { File f = new File(sourceFileName); FileInputStream fileIn = null; RandomAccessFile fileRead = null; try { //计算每块的字节数 long blockLength = f.length()/blockCount; //计算起始位置 long startPosition = blockLength*blockNo; byte[] temp = new byte[maxBufferSize]; fileIn = new FileInputStream(f); //设置读取模式为RM(如果当前文件不存在则创建文件) fileRead = new RandomAccessFile(targetFileName,"rw"); fileIn.skip(startPosition); fileRead.seek(startPosition); //当前读取的字节数 int curRedLength; //累计读取字节数的和 int totalRedLength=0; while((curRedLength = fileIn.read(temp)) >0 && totalRedLength < blockLength){ fileRead.write(temp, 0, curRedLength); totalRedLength += curRedLength; } } catch (FileNotFoundException e) { e.printStackTrace(); }catch (IOException e) { e.printStackTrace(); }finally{ try { if(fileRead != null){ fileRead.close(); } if(fileIn != null){ fileIn.close(); } }catch (IOException e) { e.printStackTrace(); } } } } import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import com.file.cope.FileCope; /** * 文件多线程拷贝测试 * @author Administrator * */ public class FileTest { public static void main(String[] args){ String sourceFileName = "E://源文件//java软件//jdk-1_5_0_19-windows-i586-p.exe"; String targetFileName = "E://源文件//java软件//jdk-1_5_0_19-windows-i586-pCode.exe"; //创建线程池 ExecutorService ex = Executors.newFixedThreadPool(20); long blockCount = 1000; long beginTime=System.currentTimeMillis(); for(int i =0 ; i<blockCount; i ++){ ex.execute(new FileCope(sourceFileName, targetFileName, blockCount, i)); } ex.shutdown(); while(true){ if(ex.isTerminated()){ long endTime=System.currentTimeMillis(); System.out.println(endTime- beginTime); break; } } } } 代码请展开