import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.RandomAccessFile;
public class FileCopyThread implements Runnable {
private long head;
private long end;
private String fileSourse;
private String fileTarget;
public String getFileSourse() {
return fileSourse;
}
public void setFileSourse(String fileSourse) {
this.fileSourse = fileSourse;
}
public String getFileTarget() {
return fileTarget;
}
public void setFileTarget(String fileTarget) {
this.fileTarget = fileTarget;
}
public FileCopyThread(long head, long end) {
super();
// TODO Auto-generated constructor stub
this.head = head;
this.end = end;
}
public void run() {
try {
RandomAccessFile rin = new RandomAccessFile(fileSourse, "r");
RandomAccessFile rout = new RandomAccessFile(fileTarget, "rw");
rin.seek(head);
rout.seek(head);
byte[] buffer = new byte[1024];
int length = 0;
while (end - rin.getFilePointer() >= 1024) {
rin.read(buffer);
rout.write(buffer);
}
length = (int) (end - rin.getFilePointer());
rin.readFully(buffer, 0, length);
rout.write(buffer, 0, length);
rout.close();
rin.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* @param args
*/
public static void main(String[] args) {
// 读入键盘输入
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
// 文件来源
String fileCopyFrom;
// 文件目标
String fileCopyTo;
try {
System.out.println("要复制的文件:");
fileCopyFrom = br.readLine();
System.out.println("文件复制到:");
fileCopyTo = br.readLine();
// 创建一个来源 File 实例
File fileIn = new File(fileCopyFrom);
// 创建 RandomAccessFile 目标实例
RandomAccessFile fileOut = new RandomAccessFile(fileCopyTo, "rw");
// 定义文件长度
long length = fileIn.length();
fileOut.setLength(length);
System.out.println("切分线程数:");
int num = Integer.parseInt(br.readLine());
// 创建对象 实例
FileCopyThread[] copy = new FileCopyThread[num];
// 创建线程 实例
Thread[] thread = new Thread[num];
// h 头;e 尾;block 块数(k)
long h = 0;
long e = 0;
long block = length / 1024;
if(block<=1)
num=1;
for (int i = 0; i < num; i++) {
// 定义 每次转移的长度
h = i * 1024*(block / num);
e = (i + 1) * 1024*(block/ num);
if (i == (num - 1))
e = length;
// 创建新 FileCopyThread实例 (h, e)
copy[i] = new FileCopyThread(h, e);
thread[i] = new Thread(copy[i]);
// 设置新实例的文件来源
copy[i].setFileSourse(fileCopyFrom);
// 设置新实例的文件目标
copy[i].setFileTarget(fileCopyTo);
// 线程启动
thread[i].start();
}
fileOut.close();
System.out.println("转移完成。");
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}