使用普通的按字節讀取,再寫入另一個文件,速度太慢。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();
}
}
}
}