package com.softeem.test8;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
public class ThreadFileCopy extends Thread {
private File source;//源文件
private File target;//目标文件
private long start;//开始位置
private long end;//结束位置
public ThreadFileCopy(File source, File target, long start, long end) {
super();
this.source = source;
this.target = target;
this.start = start;
this.end = end;
}
public void run() {
System.out.println(this.getName()+"开始拷贝");
int count = 0;
RandomAccessFile rafread = null;
RandomAccessFile rafwrite = null;
try {
rafread = new RandomAccessFile(source, "r");//只读
rafwrite = new RandomAccessFile(target, "rw");//可读可写
rafread.seek(start);
rafwrite.seek(start);
int len = 0;
byte[] b = new byte[50];
while ((len = rafread.read(b)) != -1 && count <= (end - start)) {//拷贝文件
count += len;
rafwrite.write(b, 0, len);
}
System.out.println(this.getName()+"完成");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (rafwrite != null)
rafwrite.close();
if (rafread != null)
rafread.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
File source = new File("d:\\larva搞笑虫子\\src.zip");//源文件
File target = new File("d:\\目的\\src.zip");//目标文件
long item = source.length() / 4;
for (int i = 0; i < 4; i++) {
new ThreadFileCopy(source, target, i * item, (i + 1) * item).start();//四个进程分段拷贝
}
}
}
1_mr_tangshuai
mr_tangshuai
编辑
预览
使用4个线程拷贝一个文件,实现断点下载。比如:这个文件500M,分四段下载。
最新推荐文章于 2020-07-19 20:16:50 发布