使用RandomAccessFile类采用多线程方式完成文件复制
最近遇到了一个基础类,RandomAccessFile类。学习了一下其使用方法,记录下来。
一、定义自己复制线程
public class CopyThread extends Thread {
private RandomAccessFile rf;//提供文件读取的流
private RandomAccessFile wf;//提供文件写入的流
private long startPoint; //标记文件copy的位置
public final static int COPY_SIZE=10;//每一个线程负责复制的文件大小为10*1024,差不多10kb
//初始化文件读,写,复制位置
public CopyThread(File fr, File fw, long startPoint) {
try {
this.rf = new RandomAccessFile(fr, "r");
this.wf = new RandomAccessFile(fw, "rw");
} catch (Exception e) {
e.printStackTrace();
}
this.startPoint = startPoint;
}
@Override
public void run() {
try {
//文件复制的常规操作
rf.seek(startPoint);
wf.seek(startPoint);
byte[] buffer = new byte[1024];
int len = 0;
int maxSize = 0;
while ((len = rf.read(buffer)) != -1&&maxSize<COPY_SIZE) {
wf.write(buffer, 0, len);
maxSize++;//标记复制的位置,达到10*1024,该线程任务结束
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
rf.close();
wf.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
二、主类,测试
public class TestMain {
public static void main(String[] args) throws Exception {
int COPY_SIZE = CopyThread.COPY_SIZE;
File f1 = new File("d:" + File.separator + "test01.txt");//待复制的文件
File f2 = new File("d:" + File.separator + "test02.txt");//copy的文件
if (!f1.exists()) {
System.out.println("文件不存在。");
return;
}
long length = f1.length();
int bord = (int) length / (COPY_SIZE * 1024);
bord = (int) length % (COPY_SIZE * 1024) == 0 ? bord : bord + 1;//初始化需要线程的数量
for (int i = 0; i < bord; i++) {
new CopyThread(f1, f2, i * COPY_SIZE * 1024).start();//启动线程
}
Thread.sleep(3000);//为了让所有线程全部复制完毕
System.out.println("复制完成");
}
}