使用普通的按字节读取,再写入另一个文件,速度太慢。Java提供的JavaChannel能显著提升速度(暂时不知道原理)
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;
public class FileCopy {
public static void main(String[] args) {
String from="e:/Thunder_dl_V7.9.37.4952_setup.1433748298.exe";
String to="e:/copy/target.exe";
File fileFrom=new File(from);
File fileTo=new File(to);
long start=System.currentTimeMillis();
//normalCopy(fileFrom,fileTo);
fastCopy(fileFrom, fileTo);
long end=System.currentTimeMillis();
System.out.println("复制文件所用时间是:"+(end-start)+"ms");
}
public static void normalCopy(File fileFrom,File fileTo){
int b;
FileInputStream from=null;
FileOutputStream to=null;
try {
from=new FileInputStream(fileFrom);
to=new FileOutputStream(fileTo);
while((b=from.read())!=-1){
to.write(b);
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
System.out.println("没有找到文件");
e.printStackTrace();
System.exit(-1);
} catch (IOException e) {
// TODO Auto-generated catch block
System.out.println("文件复制错误");
e.printStackTrace();
System.exit(-1);
} finally {
try {
from.close();
to.close();
} catch(IOException e){
e.printStackTrace();
}
}
}
public static void fastCopy(File fileFrom,File fileTo){
FileInputStream from=null;
FileOutputStream to=null;
FileChannel in=null;
FileChannel out=null;
try {
from=new FileInputStream(fileFrom);
to=new FileOutputStream(fileTo);
in=from.getChannel();//获取通道
out=to.getChannel();//
in.transferTo(0, in.size(), out); //java提供的复制方法
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
System.out.println("没有找到文件");
e.printStackTrace();
System.exit(-1);
} catch (IOException e) {
// TODO Auto-generated catch block
System.out.println("文件复制错误");
e.printStackTrace();
System.exit(-1);
} finally {
try {
from.close();
in.close();
to.close();
out.close();
} catch(IOException e){
e.printStackTrace();
}
}
}
}