一、多线程复制文件
思路:
- 用n个线程复制文件,将文件file等分成每个大小为file.length()/n的小份文件。
- 得到每一份的文件的"首指针"和"尾指针"
- 用随机文件流RandomAccessFile进行读写
- 控制读写时"首指针"的范围
- 原文件剩余的部分再开启新的线程进行处理
public class thread_file_copy {
public static void main(String[] args) throws FileNotFoundException {
String src = "D:\\java\\01_JAVA SE基础\\01 变量与数据类型\\视频\\avi\\01.13_变量的概述和定义格式.avi";
String des = "D:\\01.13_变量的概述和定义格式.avi";
File file = new File(src);
long len = file.length();
long start = 0, end = 0;
long threadnum = 5;
for(long i = 0; i < threadnum; i++) {
start = i*len/5;
end = (i+1)*len/5;
new file_copy(start, end, src,des).start();
}
long last = len % threadnum;
if(last != 0) {
start = end + 1;
end = len;
new file_copy(start, end, src, des).start();
}
}
}
public class file_copy extends Thread {
long start;
long end;
RandomAccessFile in = null;
RandomAccessFile out = null;
public file_copy(long start, long end, String src, String des) throws FileNotFoundException {
this.start = start;
this.end = end;
in = new RandomAccessFile(src, "rw");
out = new RandomAccessFile(des, "rw");
}
@Override
public void run() {
try {
in.seek(start);
out.seek(start);
byte[] bytes = new byte[1024];
int len = in.read(bytes);
while((len = in.read(bytes)) != -1) {
out.write(bytes, 0, len);
start = start + len;
}
in.close();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}