Java复制文件速度最快的算法
第一种方法,是采用普通的IO,Buffered流,速度一般;另一种是采用Channel流的transfer方法,速度超快。建议采用第二种方法。
public static long copyFile(File srcFile,File destDir,String newFileName){
long copySizes = 0;
if(!srcFile.exists()){
System.out.println("源文件不存在");
copySizes = -1;
}
else if(!destDir.exists()){
System.out.println("目标目录不存在");
copySizes = -1;
}
else if(newFileName == null){
System.out.println("文件名为null");
copySizes = -1;
}
else{
try {
BufferedInputStream bin = new BufferedInputStream(
new FileInputStream(srcFile));
BufferedOutputStream bout = new BufferedOutputStream(
new FileOutputStream(new File(destDir,newFileName)));
int b = 0 ,i = 0;
long t1 = System.currentTimeMillis();
while((b = bin.read()) != -1){
bout.write(b);
i++;
}
long t2 = System.currentTimeMillis();
bout.flush();
bin.close();
bout.close();
copySizes = i;
long t = t2-t1;
System.out.println("复制了" + i + "个字节\n" + "时间" + t);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return copySizes;
}
public static long copyFile2(File srcFile,File destDir,String newFileName){
long copySizes = 0;
if(!srcFile.exists()){
System.out.println("源文件不存在");
copySizes = -1;
}
else if(!destDir.exists()){
System.out.println("目标目录不存在");
copySizes = -1;
}
else if(newFileName == null){
System.out.println("文件名为null");
copySizes = -1;
}
else{
try {
FileChannel fcin = new FileInputStream(srcFile).getChannel();
FileChannel fcout = new FileOutputStream(
new File(destDir,newFileName)).getChannel();
ByteBuffer buff = ByteBuffer.allocate(1024);
int b = 0 ,i = 0;
// long t1 = System.currentTimeMillis();
long size = fcin.size();
fcin.transferTo(0,fcin.size(),fcout);
//fcout.transferFrom(fcin,0,fcin.size());
//一定要分清哪个文件有数据,那个文件没有数据,数据只能从有数据的流向
//没有数据的文件
// long t2 = System.currentTimeMillis();
fcin.close();
fcout.close();
copySizes = size;
// long t = t2-t1;
// System.out.println("复制了" + i + "个字节\n" + "时间" + t);
// System.out.println("复制了" + size + "个字节\n" + "时间" + t);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return copySizes;
}
直接影射,MappedByteBuffer
void byteMapFileCopy(String inFile,String outFile) throw* **ception
long t1=System.currentTimeMillis();
File file=new File(inFile);
FileChannel out=new FileOutputStream(new File(outFile)).getChannel();
//FileInputStream input=new FileInputStream(file);
MappedByteBuffer buffer=new FileInputStream(file).getChannel().map(FileChannel.MapMode.READ_ONLY,0,file.length());
buffer.load();
//Charset charset=Charset.defaultCharset();
//Charset charset=Charset.forName("GBK");
//CharBuffer charBuffer=charset.decode(buffer);
//System.out.println(charBuffer);
out.write(buffer);
buffer=null;
out.close();
System.out.println("花费时间"+(System.currentTimeMillis()-t1)+"测试");