多线程复制文件
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
public class MyTest {
public static void main(String[] args) throws FileNotFoundException {
File sourceFile = new File("1.网络模型的介绍.mp4");//封装文件
File targetFile = new File("网络模型的介绍.mp4");//封装目标文件
CopyThread.threadCopyFile(sourceFile,targetFile);
}
}
class CopyThread extends Thread {
private long start;
private long end;
private RandomAccessFile in;
private RandomAccessFile out;
private CopyThread(File sourceFile, File targetFile, long start, long end) throws FileNotFoundException {
this.start=start;
this.end=end;
in = new RandomAccessFile(sourceFile, "r");//读取源文件
out= new RandomAccessFile(targetFile,"rw");//写入目标文件
}
@Override
public void run() {
try {
//设置起始文件指针位置
in.seek(start);
out.seek(start);
//循环读写复制文件
int len=0;
int thLen=0;
byte[] bytes = new byte[1024 * 8];
int oldBytesLen=bytes.length;//获取此时数组的长度
long x=start;//定义临时变量,并给其赋值start
while (true){
//若未复制字节数小于原数组长度,则重新定义数组,长度为未复制的字节数
if(end-x<oldBytesLen){
bytes=new byte[(int)(end-x)];
}
len=in.read(bytes);//读
out.write(bytes,0,len);//写
thLen+=len;//统计以复制字节数
//若读写字节数小于原数组长度(即原数组被重新定义),则表示此线程复制任务完成,退出循环
if(len<oldBytesLen){
break;
}
x+=len;//更新起始位置
}
System.out.println(Thread.currentThread().getName()+":复制字节范围:["+start+","+end+"]\t复制字节数:"+thLen+"字节\t任务完成!");
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
//关闭流,释放资源
in.close();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
//多线程复制文件
public static void threadCopyFile(File sourceFile, File targetFile) throws FileNotFoundException {
long totalLen = sourceFile.length();//获取源文件长度(字节数)
int numThread = 3;//设置线程数量
long averageLen = totalLen / numThread;//计算每个线程平均复制字节数
//循环开启线程
for (int i = 0; i < numThread; i++) {
long start = i * averageLen;//计算起始字节位置
long end = (i + 1) * averageLen-1;//计算末尾字节位置
if (i == numThread - 1) {
end = totalLen;//最后一个线程将剩余字节全部复制
}
new Thread(new CopyThread(sourceFile, targetFile, start, end),"线程"+(i+1)).start();//开启线程
}
}
}
运行结果:
线程3:复制字节范围:[44632070,66948105] 复制字节数:22316035字节 任务完成!
线程2:复制字节范围:[22316035,44632069] 复制字节数:22316034字节 任务完成!
线程1:复制字节范围:[0,22316034] 复制字节数:22316034字节 任务完成!
Process finished with exit code 0