我又花了一个点,才写出这个东西,你看看。我也在测试。
import java.io.*;
class BlockCopier implements Runnable{
final int BLK_SIZE = 4096;
int curPos, bytesToRead;
RandomAccessFile in, out;
BlockCopier(String src, String dest, int start, int len){
try {
in = new RandomAccessFile(src, "r");
out = new RandomAccessFile(dest, "rw");
curPos = start;
bytesToRead = len;
in.seek(curPos);
out.seek(curPos);
} catch(Exception e){ e.printStackTrace();
}
}
public void run(){
byte[] buf = new byte[BLK_SIZE];
try {
int readBytes = in.read(buf, curPos, Math.min(BLK_SIZE, bytesToRead));
while (readBytes > 0 &&
bytesToRead > 0){
bytesToRead -= readBytes;
out.write(buf, curPos, readBytes);
curPos += readBytes;
readBytes = in.read(buf, curPos, Math.min(BLK_SIZE, bytesToRead));
}
in.close();
out.close();
} catch (Exception e){ e.printStackTrace();
}
}
}
class Copy2{
final static int FILE_BLKS = 5;
public static void main(String[] args){
int[] posbegin
;
int[] len;
Thread[] copiers;
if (args.length != 2){
System.out.println("Usage: CopyMulThread src_file dest_file");
System.exit(0);
}
posbegin
= new int[FILE_BLKS];
len = new int[FILE_BLKS];
copiers = new Thread[FILE_BLKS];
/**
* Set block begin
positions and end positions
*/
File file = new File(args[0]);
int blkSize = (int)file.length() / FILE_BLKS;
posbegin
[0] = 0;
for (int i = 1;
i< FILE_BLKS;
++i){
posbegin
= posbegin
[i-1] + blkSize;
len = blkSize;
}
len[FILE_BLKS-1] = (int)file.length() - posbegin
[FILE_BLKS-1];
/**
* Start several thread todo
the job
*/
for (int i = 0;
i< FILE_BLKS;
++i){
copiers = new Thread(new BlockCopier(args[0], args[1], posbegin
, len));
copiers.start();
}
}
}