本文采用四種方法將同樣的數據從一個文件復制到另外一個文件中,並對其進行計時統計,並作了結果對比
四種方法分別為:
1,用基本字節流一次讀寫一個字節
2,用基本字節流一次讀寫一個字節數組
3,用高效字節流一次讀寫一個字節
4, 用高效字節流一次讀寫一個字節數組
下面來看代碼:
package a003;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class TestDemo {
public static void main(String[] args) throws IOException{
long start=System.currentTimeMillis();
Method1("h:\\a.txt","h:\\ed.txt");
long end=System.currentTimeMillis();
System.out.println("總耗時:"+(end-start)+"毫秒");
}
//用高效字節流一次讀寫一個字節數組
public static void Method4(String src,String dest)throws IOException{
BufferedInputStream bis=new BufferedInputStream(new FileInputStream(src));
BufferedOutputStream bos=new BufferedOutputStream(new FileOutputStream(dest));
byte[] bys=new byte[1024];
int len=0;
while((len=bis.read(bys))!=-1){
bos.write(bys,0,len);
}
bis.close();
bos.close();
}
//用高效字節流一次讀寫一個字節
public static void Method3(String src,String dest)throws IOException{
BufferedInputStream bis=new BufferedInputStream(new FileInputStream(src));
BufferedOutputStream bos=new BufferedOutputStream(new FileOutputStream(dest));
int len=0;
while((len=bis.read())!=-1){
bos.write(len);
}
bis.close();
bos.close();
}
//用基本字節流一次讀寫一個字節
public static void Method1(String src,String dest)throws IOException{
FileInputStream fis=new FileInputStream(src);
FileOutputStream fos=new FileOutputStream(dest);
int len=0;
while((len=fis.read())!=-1){
fos.write(len);
}
fis.close();
fos.close();
}
//用基本字節流一次讀寫一個字節數組
public static void Method2(String src,String dest)throws IOException{
FileInputStream fis=new FileInputStream(src);
FileOutputStream fos=new FileOutputStream(dest);
byte[] bys=new byte[1024];
int len=0;
while((len=fis.read(bys))!=-1){
fos.write(bys,0,len);
}
fis.close();
fos.close();
}
}
計算結果統計對比:
method1:總耗時:127毫秒
method2:總耗時:1毫秒
method3:總耗時:32毫秒
method4:總耗時:1毫秒
從上面的輸出結果可以看出,在同等情況下,一次傳輸一個字節數組的方法的傳輸速度明顯高於一次傳輸一個字節的方法,不管是高效字節流還是普通的字節流中,盡管在method2和method4都為一毫秒,看起來似乎兩個傳輸速度幾乎相同。
但是,問題是因為文中測試的數據量太小,如果是數據量足夠大的話,高效字節流的優勢肯定會體現出來,讀者不妨自己找一個大一點的數據試試,比如視頻文件。
文中難免有不足之處,還望大家不吝糾正和指導,謝謝