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 srcFile = new File("叶丽仪 - 新上海滩.mp3");
//获取文件的总字节数
long totalLength = srcFile.length();
//totalLength = 310;
//定义线程数量
long threadNum = 3;
//每个线程平均要复制的字节数
long pj = totalLength / threadNum;
for (long i = 0; i < threadNum; i++) {
//每个线程要复制的起始位置和终止位置
long start = i * pj;
long end = (i + 1) * pj-1;
//System.out.println("线程"+i+"复制的起始位置"+start+"和终止位置"+end);
new CopyFileThread(srcFile, "G:\\demo.mp3" , start, end).start();
}
//如果线程的总字节数,不够线程均分,那就再补一个线程。
long yu = totalLength % threadNum;
if (yu != 0) {
long start = pj * threadNum;
long end = totalLength;
//System.out.println("补的线程" + "复制的起始位置" + start + "和终止位置" + end);
new CopyFileThread(srcFile, "G:\\demo.mp3", start, end).start();
}
}
}
class CopyFileThread extends Thread {
RandomAccessFile in;
RandomAccessFile out;
private long start;
private long end;
/**
* @param srcFile 源文件
* @param target 目标文件
* @param start 起始位置
* @param end 终止位置
*/
public CopyFileThread(File srcFile, String target, long start, long end) throws FileNotFoundException {
in = new RandomAccessFile(srcFile, "rw");
out = new RandomAccessFile(target, "rw");
this.start = start;
this.end = end;
}
@Override
public void run() {
try {
//设置复制起始位置
in.seek(start);
out.seek(start);
int len = 0;
byte[] bytes = new byte[1024*8];
while (start<end&&(len=in.read(bytes))!=-1) {
out.write(bytes,0,len);
//累计一下,每个线程复制的字节数
start+=len;
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
07-18
490
09-26