//用多线程复制文件
//先把文件分割为几个部分,这边把它分割成了4份,所以for循环4次,建立4个线程
//通过begin和end两个参数来决定分割后文件数据的区间,所以给SplitFile类对象传入begin和end两个参数
//SplitFile继承了Thread类,run方法中就是把旧文件的数据区间复制到新文件的过程
import java.io.*;
public class ThreadCopyDemo {
public static void main(String[] args) throws Exception {
File srcFile = new File("队列.png");// 源文件路径
File orgFile = new File("a.png");// 复制文件路径
ThreadCopyDemo demo = new ThreadCopyDemo();
demo.analysisFile(srcFile, orgFile, 4);// 4为线程数,也是把文件分割的份数
}
public void analysisFile(File srcFile, File orgFile, int threadNum) {
// 文件长度
int length = (int) srcFile.length();
// 分割文件的长度
int splitNum;
// 确定文件分割后每份的长度
if (length / threadNum * threadNum == length) {
splitNum = length / threadNum;
} else {
splitNum = length / threadNum + 1;
}
int skipPostion = -1;
int readNum = 0;
// 确定每一份文件分割的起始和终止
for (int i = 1; i <= threadNum; i++) {
if (i != threadNum) {
readNum = i * splitNum;
} else {
readNum = length - readNum;
}
SplitFile sf = new SplitFile(skipPostion + 1, readNum, srcFile,
orgFile);
sf.start();
skipPostion = i * splitNum;
}
}
class SplitFile extends Thread {
private int begin;
private int end;
private File srcFile;
private File orgFile;
public SplitFile(int begin, int end, File srcFile, File orgFile) {
super();
this.begin = begin;
this.end = end;
this.srcFile = srcFile;
this.orgFile = orgFile;
}
public void run() {
try {
RandomAccessFile raf_r = new RandomAccessFile(srcFile, "rw");
RandomAccessFile raf_w = new RandomAccessFile(orgFile, "rw");
// 从传来的起始位置读和写,直到终止位置结束
raf_r.skipBytes(begin);
raf_w.seek(begin);
byte[] buf = new byte[1024];
int len = 0;
for (int size = 0; len <= end && size != -1; size = raf_r
.read(buf)) {
len = len + size;
raf_w.write(buf, 0, size);
}
raf_w.close();
raf_r.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
}
多线程复制文件
最新推荐文章于 2023-03-02 10:02:57 发布