多线程文件拷贝,具体使用了RandomAccessFile类,对源文件进行随机读,对目标文件进行随机写入。需注意需在线程内部去实例化RandomAccessFile类,进行操作避免资源句柄共享造成异常。
-
import java.io.File;
-
import java.io.IOException;
-
import java.io.RandomAccessFile;
-
-
public class FixedFile {
-
-
public static void main(String[] args) throws Exception {
-
File f = new File("a.txt");
-
long length = f.length();
-
System.out.println(length);
-
int threadNum = 3;
-
int split ;
-
if(length%3==0){
-
split = (int) (length/3);
-
} else{
-
split = (int) (length/3) + 1;
-
}
-
System.out.println(split);
-
-
String src = "a.txt";
-
String dest = "b.txt";
-
//先建立目标文件
-
RandomAccessFile destFile = new RandomAccessFile(dest,"rw");
-
destFile.setLength(length);
-
destFile.close();
-
-
for(int i =0; i<threadNum;i++ ) {
-
new Thread(new MultiCopy(src,dest, i*split,split) ).start();
-
}
-
}
-
-
}
-
class MultiCopy implements Runnable{
-
-
private String from;
-
private String dest;
-
private int offset;
-
private int length;
-
public MultiCopy(String from,String dest,int offset, int length) {
-
this.from = from;
-
this.dest=dest;
-
this.offset=offset;
-
this.length=length;
-
}
-
-
@Override
-
public void run() {
-
RandomAccessFile srcFile = null;
-
RandomAccessFile destFile = null;
-
try {
-
srcFile = new RandomAccessFile(from,"r");
-
destFile = new RandomAccessFile(dest,"rw");
-
srcFile.seek(offset);
-
destFile.seek(offset);
-
byte [] buff = new byte[1024]; //缓冲区大小
-
int num = (length % 1024 ==0) ? (length / 1024) :(length / 1024 + 1) ; //迭代次数
-
for(int i=0;i<num;i++) {
-
int perLength = srcFile.read(buff);
-
if(perLength != -1) {
-
destFile.write(buff);
-
}
-
}
-
} catch (Exception e) {
-
e.printStackTrace();
-
} finally {
-
try {
-
destFile.close();
-
srcFile.close();
-
} catch (IOException e) {
-
e.printStackTrace();
-
}
-
}
-
}
-
-
}
阅读(1581) | 评论(0) | 转发(0) |