Java IO(五) 緩衝流
阿新 • • 發佈:2020-11-28
緩衝流是一種處理流,需要套在節點流上使用,能提高寫入或讀取的速度
測試未加緩衝流和加緩衝流在速度上的差異,拷貝870M大小的檔案,BufferedInputStream 位元組輸入流和BufferedOutputStream位元組輸出流
package com.mike.io.eg; import java.io.IOException; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.File; /** * @author mike * @date 2020-11-26 * @desc 位元組輸入緩衝流,測試無緩衝流拷貝檔案 */ public class BufferedInputStreamDemo { public static void main(String[] args) { //定義輸入流 FileInputStream fis = null; FileOutputStream fos = null; File source = new File("D:\\系統映象\\ubuntu-18.04.4-live-server-amd64.iso"); File target = new File("F:\\ubuntu-18.04.4-live-server-amd64.iso"); try { long start = System.currentTimeMillis(); fis = new FileInputStream(source); fos = new FileOutputStream(target); byte[] buffer = new byte[1024]; int len = 0; while((len = fis.read(buffer)) != -1) { fos.write(buffer,0,len); } long end = System.currentTimeMillis(); System.out.println("拷貝成功,一共耗時" + (end - start) / 60 + "s" );//74s } catch (IOException e) { e.printStackTrace(); } finally { try { fis.close(); fos.close(); } catch (IOException e) { e.printStackTrace(); } } } }
輸出結果
package com.mike.io.eg; import java.io.IOException; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; /** * @author mike * @date 2020-11-26 * @desc 位元組緩衝輸出流,測試加緩衝流拷貝檔案時間 */ public class BufferedOutputStreamDemo1 { public static void main(String[] args) { File source = new File("D:\\系統映象\\ubuntu-18.04.4-live-server-amd64.iso"); File target = new File("F:\\ubuntu-18.04.4-live-server-amd64.iso"); BufferedInputStream bis = null; BufferedOutputStream bos = null; try { long start = System.currentTimeMillis(); bis = new BufferedInputStream(new FileInputStream(source)); bos = new BufferedOutputStream(new FileOutputStream(target)); int len = 0; byte[] buffer = new byte[1024]; while((len = bis.read(buffer)) != -1) { bos.write(buffer,0,len); } long end = System.currentTimeMillis(); System.out.println("拷貝完成,一共耗時" + (end-start)/60 + "s" ); } catch (IOException e) { e.printStackTrace(); } finally { try { bis.close(); bos.close(); } catch (IOException e) { e.printStackTrace(); } } } }
輸出結果
測試結果表明使用緩衝流讀寫檔案時間會縮短3分之一,強烈建議使用緩衝流