代码直接看吧,里面有注释。不了解可以评论,交流
import java.io.File;
public class Test {
public static void main(String[] args) {
//需要复制的文件
File sourceFile = new File("F:\\PotPlayerSetup64.exe");
//需要复制到哪
File targetFile = new File("D:\\PotPlayerSetup64.exe");
//文件大小
long length = sourceFile.length();
//开启的线程数
int threadNums = 4;
//取余后剩下的length
long modl = length % threadNums;
//每个线程复制多少length
long desl = length / threadNums;
//开启线程
for (int i = 0; i < threadNums; i++) {
MyRunable runnable = new MyRunable(desl * i, desl * (i + 1), sourceFile, targetFile);
new Thread(runnable).start();
}
//最后剩下的Length进行复制
if (modl != 0) {
MyRunable runnable = new MyRunable(desl * 4, desl * 4 + modl, sourceFile, targetFile);
new Thread(runnable).start();
}
}
}
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
public class MyRunable implements Runnable {
private long start; //读取起点
private long end; //读取结束位置
private File sourceFile;
private File targetFile;
public MyRunable(long start, long end, File sourceFile, File targetFile) {
this.start = start;
this.end = end;
this.sourceFile = sourceFile;
this.targetFile = targetFile;
}
@Override
public void run() {
RandomAccessFile sourceRandom = null;
RandomAccessFile targetRandom = null;
try {
sourceRandom = new RandomAccessFile(sourceFile, "rw");
targetRandom = new RandomAccessFile(targetFile, "rw");
//设置读入起点,和写入起点
sourceRandom.seek(start);
targetRandom.seek(start);
//设置1024大小的缓冲区
byte[] bytes = new byte[1024];
int length;
//计算1024复制几次(这里不懂,私聊)
int divisor = (int) ((end - start) / 1024);
//不足1024的最后处理
int mod = (int) ((end - start) % 1024);
while (divisor != 0) {
length = sourceRandom.read(bytes);
start += length;
targetRandom.write(bytes, 0, length);
divisor = (int) ((end - start) / 1024);
}
//将不足1024的最后部分进行复制
int lastLength = sourceRandom.read(bytes, 0, mod);
targetRandom.write(bytes, 0, lastLength);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
//关闭流释放资源
try {
sourceRandom.close();
targetRandom.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}