在这个比拼硬件的时代,多线程拷贝文件并不能提高多少拷贝文件的时间,但是多线程的重要性大家都不言而喻,下面是多线程拷贝的具体步骤:
下面展示一些 内联代码片
。
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
public class FileSplitCopy extends Thread{
/**源文件*/
private File source ;
/**目标文件*/
private File target;
/**开始拷贝位置*/
private long start;
/**结束拷贝位置*/
private long end;
public FileSplitCopy(File source, File target, long start, long end) {
super();
this.source = source;
this.target = target;
this.start = start;
this.end = end;
}
@Override
public void run() {
try(
RandomAccessFile read = new RandomAccessFile(source, "r");
RandomAccessFile write = new RandomAccessFile(target, "rw");
) {
//跳过指定个字节发生下一次读写
read.seek(start);
write.seek(start);
byte[]b=new byte[1024];
int len =0;
//用于统计一条线程读取的线程数
int count = 0;
System.out.println("开始拷贝");
while((len=read.read(b))!=-1) {
count += len;
//如果目前读取的总字节数超过了每一段的长度则停止读取(当前线程的任务结束)
//前提:不是最后一条线程
if(count>=(end-start)&&"t3".equals(getName())) {
break;
}
}
}catch(IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
File source = new File("F:\\英雄时刻\\38123882\\英雄时刻_20190730-13点50分54s.avi");
File target = new File("D:\\a\\英雄时刻_20190730-13点50分54s.avi");
//平均获取每一段长度
long item = source.length()/4;
for (int i = 0; i <4; i++) {
FileSplitCopy fsc =new FileSplitCopy(source,target,i*item,(i+1)*item);
fsc.setName("t"+i);
fsc.start();
}
}
}
```javascript
// An highlighted block
var foo = 'bar';