import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;public class OneThreadCopy {
public static void main(String[] args) throws FileNotFoundException {
//源文件
File source=new File("f:/test/navicat150_premium_cs_x64.exe");
//目标文件
File destFile=new File("f:/test/navicat4.exe");
//获取文件长度
long length=source.length();
//预计线程数
long threadNum=3;
//分割文件
long average=length/threadNum;
//创建多个线程
for (int i = 0; i < threadNum; i++) {
//0~100,101~200,201~300
//开始位置
long start=i*(average+1);
//结束位置
long end=(i+1)*average;
//启动线程
new Thread(new CopyThread(start,end,source,destFile)).start();
}
//有剩余在增加一个线程
if(length%threadNum!=0) {
new Thread(new CopyThread(average*threadNum+1, length, source, destFile)).start();
}
}
}
class CopyThread implements Runnable{
private long start;
private long end;
public RandomAccessFile rsource=null;
public RandomAccessFile rdestFile=null;
public CopyThread(long start, long end, File source, File destFile) throws FileNotFoundException {
this.start = start;
this.end = end;
this.rsource=new RandomAccessFile(source, "rw");
this.rdestFile=new RandomAccessFile(destFile, "rw");
}
@Override
public void run() {
try {
//光标移到初始位置
rsource.seek(start);
rdestFile.seek(start);
//缓存区
byte []bytes=new byte[1024*1024];
//读取的个数
int len=0;
//源文件里光标的位置
long point=rsource.getFilePointer();
while(point<=end&&(len=rsource.read())!=-1) {
//把长度为len的字节写入
rdestFile.write(bytes,0,len);
//光标移动len
point+=len;
}
} catch (Exception e) {
e.printStackTrace();
}finally {
try {
rsource.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
rdestFile.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
利用多线程和IO流进行文件复制
最新推荐文章于 2023-04-25 19:06:33 发布