java中串流是什么,java中利用串流裝飾器進行文件讀寫的速度對比

本文采用四種方法將同樣的數據從一個文件復制到另外一個文件中,並對其進行計時統計,並作了結果對比

四種方法分別為:

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都為一毫秒,看起來似乎兩個傳輸速度幾乎相同。

但是,問題是因為文中測試的數據量太小,如果是數據量足夠大的話,高效字節流的優勢肯定會體現出來,讀者不妨自己找一個大一點的數據試試,比如視頻文件。

文中難免有不足之處,還望大家不吝糾正和指導,謝謝

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值