FileInputStream與BufferedInputStream的對比


復制代碼
FileInputStream inputStream = new FileInputStream("d://vv.mp4"); FileOutputStream outputStream = new FileOutputStream("v.mp4"); int len; // 一次讀取一個字節,每讀取一個字節都要實現一次與硬盤的交互操作 while ((len = inputStream.read()) != -1) { outputStream.write(len); } 
復制代碼

 

復制代碼
FileInputStream inputStream = new FileInputStream("d://vv.mp4"); FileOutputStream outputStream = new FileOutputStream("v.mp4"); int len; byte[] bs = new byte[1024]; //這里添加了一個緩存數組,每次從硬盤讀取1024個字節,也就是說,每讀取1024個字節才與硬盤實現一次交互 while ((len = inputStream.read(bs)) != -1) { outputStream.write(bs, 0, len); } 
復制代碼

 

 

復制代碼
FileInputStream inputStream = new FileInputStream("d://vv.mp4"); BufferedInputStream bis = new BufferedInputStream(inputStream); //默認有8M的緩存 FileOutputStream outputStream = new FileOutputStream("IP.mp4"); BufferedOutputStream bos = new BufferedOutputStream(outputStream); int len; byte[] bs = new byte[1024]; while ((len = bis.read(bs)) != -1) { bos.write(bs, 0, len); //先從硬盤讀出8M到緩存中。然后read,這里的read並不是從硬盤中讀取,而是從那8M緩存(內存)中讀取,自然要比從硬盤中快得多。8M緩存用完后又會從硬盤補充(也就是說,一次從硬盤獲取8M字節的數據) 。每8M與硬盤交互一次 }
復制代碼

 

 

以上三種方式在效率上遞增,用BufferedInputStream效率最高(特別是對小文件)。

另外,對於BufferOutputStream和FileOutputStream也是一樣,BufferOutputStream的write是把字節寫入自帶的緩存中(flush之后才向硬盤寫),而FileOutputStream則是一次一個字節的向硬盤寫。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM