多线程复制文件
?
?
import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.IOException;import java.io.RandomAccessFile;public class MyThread implements Runnable{public String filepath = "";public String srcfile="";public long startposition;public long endposition;RandomAccessFile file;public MyThread(String srcfile,String filepath,long startposition,long endposition){this.srcfile = srcfile;this.filepath = filepath;this.startposition = startposition;this.endposition = endposition;}@Overridepublic void run() {FileInputStream fio = null;Thread thread = Thread.currentThread();System.out.println(thread.getId());try {fio = new FileInputStream(this.srcfile);byte[] temp = new byte[1024];//1kint templength;fio.skip((int)this.startposition);file = new RandomAccessFile(this.filepath,"rw");file.seek((int)this.startposition);while((templength = fio.read(temp)) > 0 && this.startposition <= this.endposition){file.write(temp,0,templength);this.startposition = this.endposition;}} catch (FileNotFoundException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}finally{try {fio.close();file.close();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}}?
测试 方法
package com;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.IOException;public class UploadFile {public static void main(String[] args) {FileInputStream fio = null;String srcfile="c:\\2013年春节放假通知.docx";String targetfile = "c:\\huangbiao.docx";try {fio = new FileInputStream(srcfile);long length = fio.available();System.out.println(length);int tnum = (int) (length%(1024*1024)==0?length/(1024*1024):length/(1024*1024)+1);for(int i=0;i<tnum;i++){MyThread myThread = null;if((length-(i-1)*1024*1024)>0){myThread = new MyThread(srcfile,targetfile,i*1024*1024,(i+1)*1024*1024-1);}else{myThread = new MyThread(srcfile,targetfile,i*1024*1024,length);}Thread thread = new Thread(myThread);thread.start();}} catch (FileNotFoundException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}finally{try {fio.close();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}}?