import java.io.*;
public class Demo {
static int threadNum = 3;
public static void main(String[] args) throws Throwable {
for (int i = 0; i < threadNum; i++) {
RandomAccessFile rafReader = new RandomAccessFile("C:\\Users\\Administrator\\Desktop\\test.zip", "rw");
RandomAccessFile rafWriter = new RandomAccessFile("C:\\Users\\Administrator\\Desktop\\raftest.zip", "rwd");
// 共 25 字节 取1/3
long length = rafReader.length();
long splice = length / threadNum;
rafWriter.setLength(length);
Long startIndex = i * splice;
Long endIndex = (i + 1) * splice-1;
Long total = endIndex -startIndex;
if (i == threadNum - 1) {
// 代表最后一个线程
endIndex = length - 1;
}
Long finalEndIndex = endIndex;
new Thread(() -> {
try {
rafReader.seek(startIndex);
rafWriter.seek(startIndex);
byte[] bytes = new byte[1024];
int len = 0;
while ((len = rafReader.read(bytes)) != -1) {
if(len>total){
break;
}
rafWriter.write(bytes, 0, len);
}
rafReader.close();
rafWriter.close();
System.out.println("当前线程:" + Thread.currentThread().getName() + " start:" + startIndex + " end:" + finalEndIndex+" 文件总大小:"+length/1024 +"KB");
} catch (Exception e) {
e.printStackTrace();
} finally {
if (rafReader != null) {
try {
rafReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (rafWriter != null) {
try {
rafWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}).start();
}
}
}
多线程读写文件Demo
最新推荐文章于 2021-02-03 20:39:26 发布