您的位置:首页 > 编程语言 > Java开发

6.多线程文件拷贝

2016-12-07 14:03 316 查看
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;

class MyTask implements Runnable{
private RandomAccessFile src;
private RandomAccessFile des;
private long position;    //当前线程对文件操作的开始位置
private long blockSize;   //当前线程对文件操作的总共大小
private long curSendSize; //当前线程已经处理的文件大小

public MyTask(File src, File des, long position, long blockSize) throws FileNotFoundException{
this.src = new RandomAccessFile(src, "r");
this.des = new RandomAccessFile(des, "rw");
this.position = position;
this.blockSize = blockSize;
this.curSendSize = 0;
}

public void run(){
try {
src.seek(position);
des.seek(position);

long count = 0;
byte[] buff = new byte[1024*8];

while ((count = src.read(buff)) > 0){
des.write(buff);
curSendSize += count;
if ((curSendSize+1024*8) > blockSize){
byte[] newBuff = new byte[(int) (blockSize-curSendSize)];
src.read(newBuff);
des.write(newBuff);
break;
}
}

} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally{

try {
if (src != null){
src.close();
}
if (des != null){
des.close();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}
}
}

public class TestDemo {
private static final int BLOCK_SIZE = 20*1024*1024;  //文件每20M创建一个线程

public static void main(String[] args) throws IOException, InterruptedException {
// TODO Auto-generated method stub
File src = new File("E:/copy1.mp4");
File des = new File("E:/copy2.mp4");
if (!des.exists()){
des.createNewFile();
}

long begin = System.currentTimeMillis();
long fileSize = src.length();
for (long i = 0; i < fileSize; i += BLOCK_SIZE){
if ((i+BLOCK_SIZE) > fileSize){   //文件剩余部分大小不足20M,新的block_size为fileSize-i
MyTask task = new MyTask(src, des, i, fileSize-i);
Thread thread = new Thread(task);
thread.start();
thread.join();
}
MyTask task = new MyTask(src, des, i, BLOCK_SIZE);
Thread thread = new Thread(task);
thread.start();
thread.join();
}
long end = System.currentTimeMillis();
System.out.println("spend time:" + (end-begin) + "s");
System.out.println("main over");
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息