package com.phone.week5.day1;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.RandomAccessFile;
import java.util.Scanner;
public class MulteThreadCopyFile {
public static void main(String[] args) throws Exception {
File src = new File(“D:\150720\周末作业\李荣正.rar”);
File des = new File(“d:/lrz.rar”);
File config = new File(des.getParent(), des.getName() + “.config”);
Scanner scanner = new Scanner(System.in);
System.out.println(“请输入线程的个数”);
int count = scanner.nextInt();
RandomAccessFile rafConfig = new RandomAccessFile(config, “rw”);//记录上次停止时copy的的文件指针的位置
rafConfig.setLength(8 * count); //设置文件的大小为8*线程数 4个线程32
rafConfig.close();
long countPerThread = src.length() / count; // 400 / 3 = 133
for (int i = 0; i < count; i++) {
long from = i * countPerThread;
long to;
if(i == count - 1){
to = src.length();
}else{
to = (i + 1) * countPerThread;
}
new CopyThread(src, des, config, from, to, i).start();
}
scanner.close();
// 400 3 0 133 133 266 266 399 400
// 30000有效代码
}
}
package com.phone.week5.day1;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
public class CopyThread extends Thread {
private File src; //数据源
private File des; //目的地
private long from; //从哪开始
private long to; //到哪结束
private File config; //保存断点的地方
private int index; //表示当前线程的索引
public CopyThread(File src, File des, File config, long from, long to, int index) {
this.src = src;
this.des = des;
this.from = from;
this.to = to;
this.index = index;
this.config = config;
}
@Override
public void run() {
RandomAccessFile rafSrc = null; //数据源随机流
RandomAccessFile rafDes = null; //目的地随机流
RandomAccessFile rafConfig = null; //记录断点的随机流
try {
rafConfig = new RandomAccessFile(config, "rw");
rafSrc = new RandomAccessFile(src, "r"); //读的随机流
rafDes = new RandomAccessFile(des, "rw");
rafDes.setLength(rafSrc.length()); //设置目的地的大小
System.out.println("index="+index);
rafConfig.seek(8 * index);//根据线程的索引的,来决定读取配置文件中的第几个8个字节
long pointer = rafConfig.readLong(); //读8个字节进来
if(pointer == 0){
pointer += from; //如果为0,设置开始的位置为从头开始
}
rafSrc.seek(pointer); //设置读的指针
rafDes.seek(pointer); //设置写的指针
byte[] buff = new byte[1024]; //声明一个中转数组
int len = -1;
while((len = rafSrc.read(buff)) != -1){
rafDes.write(buff, 0, len); //开始写
rafConfig.seek(8 * index); //设置指针的位置
rafConfig.writeLong(rafDes.getFilePointer());//从写的随机流的当前指针位置开始写8个字节进来
//如果读的文件的指针已经大于结束位置,表示已经读完
if(rafSrc.getFilePointer() >= to){
break;
}
//System.out.println(Thread.currentThread().getName() + "正在copy");
}
} catch (IOException e) {
e.printStackTrace();
}finally{
try {
rafSrc.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
rafDes.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
rafConfig.close();
config.delete();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}