package org.mobiletrain.demo03;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
class FileCopy implements Runnable {
private File src;// 源文件
private File tar;// 目标文件
private int n;// 分几部分
private int no;// 每部分的编号
public FileCopy(File src, File tar, int n, int no) {
this.src = src;
this.tar = tar;
this.n = n;
this.no = no;
}
@Override
public void run() {
try {
RandomAccessFile rafsrc = new RandomAccessFile(src, "r");
RandomAccessFile raftar = new RandomAccessFile(tar, "rw");
long len = src.length();
long size = len % n == 0 ? len / 4 : len / 4 + 1;// 每部分的字节数
byte[] b = new byte[1024 * 8];// 每次读取的文件大小
int num = 0;// 每次读取的字节数
long start = size * no;// 读写的起始位置
rafsrc.seek(start);
raftar.seek(start);
int sum = 0;// 累加每次读取个数
while ((num = rafsrc.read(b)) != -1 && sum < size) {
raftar.write(b, 0, num);
sum += num;
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
public class TestFileCopy {
// 1.复制文件。c:--》D:
// 多线程:n个线程
public static void main(String[] args) {
File src = new File("C:/pdf.zip");
File tar = new File("c:/pdf_bak.zip");
int n = 4;// 分几部分复制
for (int i = 0; i < n; i++) {// 每一部分的编号
new Thread(new FileCopy(src, tar, n, i)).start();
}
}
}