利用多个线程可实现对文件的复制效率更高(小文件复制)
public class MyTest2 {
public static void main(String[] args) throws IOException {
new CopyThread(0).start();
new CopyThread(1024*1024*2).start();
new CopyThread(1024*1024*4).start();
new CopyThread(1024*1024*6).start();
new CopyThread(1024*1024*8).start();
}
}
class CopyThread extends Thread{
int filepointer;
public CopyThread(int filepointer) {
this.filepointer=filepointer;
}
@Override
public void run() {
try {
File sourcefile = new File("C:\\Users\\Administrator\\Desktop\\test\\许巍-歌曲大联唱.mp3");
File targetfile = new File("C:\\Users\\Administrator\\Desktop\\test\\许巍-歌曲大联唱copy.mp3");
CopyFile(filepointer, sourcefile, targetfile);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}catch (Exception e) {
e.printStackTrace();
}
}
private void CopyFile(long filepointer, File sourcefile, File targetfile) throws IOException {
RandomAccessFile read= new RandomAccessFile(sourcefile,"rw");
RandomAccessFile write = new RandomAccessFile(targetfile, "rw");
int len=0;
byte[] bytes = new byte[0];
bytes=new byte[1024*1024*2];
read.seek(filepointer);
write.seek(filepointer);
len=read.read(bytes);
write.write(bytes,0,len);
filepointer = read.getFilePointer();
System.out.println(filepointer);
read.close();
write.close();
}
}
采用多个线程对象复制大文件
- 大文件按照占用空间大小量级创建线程数,比如3.83G,可以创建三个线程,用来复制前三个G;
- 最后的部分再创建新的线程复制即可,不可以放在循环中复制,那样就会复制出4个G的文件副本;
- 子线程类中需要加入判断,即复制的开始指针总是小于终止指针,即start<end,这样才能保证复制完全,不会出现负寻址异常;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
public class MyTest2 {
public static void main(String[] args) throws IOException {
//
File sourcefile = new File("G:\\64WIN7.GHO");
File targetfile = new File("C:\\Users\\Administrator\\Desktop\\test\\64WIN7.GHO");
long length = sourcefile.length();
System.out.println(length);
//创建三个线程复制大文件;
long threadNum=3;
long singlecopy = length / 3;
for (long i = 0; i < threadNum; i++) {
long start=singlecopy*i;
long end=(singlecopy*(i+1))-1;
System.out.println(end);
new CopyThread(start,end,sourcefile,targetfile).start();
}
//创建新的线程,复制剩下的数据
long yu = length % threadNum;
if (yu!=0){
long start=singlecopy*threadNum;
long end=length;
System.out.println(end);
new CopyThread(start,end,sourcefile,targetfile).start();
}
}
}
class CopyThread extends Thread{
long start;
long end;
RandomAccessFile read;
RandomAccessFile write;
public CopyThread(long start, long end, File sourcefile, File targetfile) throws FileNotFoundException {
this.start=start;
this.end=end;
read= new RandomAccessFile(sourcefile,"rw");
write = new RandomAccessFile(targetfile, "rw");
}
@Override
public void run() {
try {
read.seek(start);
write.seek(start);
int len=0;
byte[] bytes=new byte[1024*1024];
while ((start < end)&&(len=read.read(bytes))!=-1){
start+=len;
write.write(bytes,0,len);
}
read.close();
write.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}