Java字節(jié)緩沖流原理與用法詳解
本文實例講述了Java字節(jié)緩沖流原理與用法。分享給大家供大家參考,具體如下:
一 介紹
BufferInputStresm和BufferOutputStream
這兩個流類為IO提供了帶緩沖區(qū)的操作,一般打開文件進行寫入或讀取操作時,都會加上緩沖,這種流模式提高了IO的性能。
二 各類中方法比較
從應(yīng)用程序中把輸入放入文件,相當于將一缸水倒入另外一個缸中:
FileOutputStream的write方法:相當于一滴一滴地把水“轉(zhuǎn)移過去。
DataOutputStream的writeXXX方法:相當于一瓢一瓢地把水轉(zhuǎn)移過去。
BufferOutputStream的write方法:相當于一瓢一瓢先把水放入的桶中,再將桶中的水倒入缸中,性能提高了。
三 應(yīng)用——帶緩沖區(qū)的拷貝
/** * 進行文件的拷貝,利用帶緩沖的字節(jié)流 * @param srcFile * @param destFile * @throws IOException */ public static void copyFileByBuffer(File srcFile,File destFile)throws IOException{ if(!srcFile.exists()){ throw new IllegalArgumentException("文件:"+srcFile+"不存在"); } if(!srcFile.isFile()){ throw new IllegalArgumentException(srcFile+"不是文件"); } BufferedInputStream bis = new BufferedInputStream( new FileInputStream(srcFile)); BufferedOutputStream bos = new BufferedOutputStream( new FileOutputStream(destFile)); int c ; while((c = bis.read())!=-1){ bos.write(c); bos.flush();//刷新緩沖區(qū) } bis.close(); bos.close(); }
四 應(yīng)用——單字節(jié),不帶緩沖的拷貝
/** * 單字節(jié),不帶緩沖進行文件拷貝 * @param srcFile * @param destFile * @throws IOException */ public static void copyFileByByte(File srcFile,File destFile)throws IOException{ if(!srcFile.exists()){ throw new IllegalArgumentException("文件:"+srcFile+"不存在"); } if(!srcFile.isFile()){ throw new IllegalArgumentException(srcFile+"不是文件"); } FileInputStream in = new FileInputStream(srcFile); FileOutputStream out = new FileOutputStream(destFile); int c ; while((c = in.read())!=-1){ out.write(c); out.flush(); } in.close(); out.close(); }
五 測試——各種拷貝比較
package com.imooc.io; import java.io.File; import java.io.IOException; public class IOUtilTest4 { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub try { long start = System.currentTimeMillis(); IOUtil.copyFileByByte(new File("e:\\javaio\\demo.mp3"), new File( "e:\\javaio\\demo2.mp3")); //兩萬多毫秒 long end = System.currentTimeMillis(); System.out.println(end - start ); start = System.currentTimeMillis(); IOUtil.copyFileByBuffer(new File("e:\\javaio\\demo.mp3"), new File( "e:\\javaio\\demo3.mp3"));//一萬多毫秒 end = System.currentTimeMillis(); System.out.println(end - start ); start = System.currentTimeMillis(); IOUtil.copyFile(new File("e:\\javaio\\demo.mp3"), new File( "e:\\javaio\\demo4.mp3"));//7毫秒 end = System.currentTimeMillis(); System.out.println(end - start ); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
六 測試結(jié)果
13091
9067
10
更多java相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《Java面向?qū)ο蟪绦蛟O(shè)計入門與進階教程》、《Java數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Java操作DOM節(jié)點技巧總結(jié)》、《Java文件與目錄操作技巧匯總》和《Java緩存操作技巧匯總》
希望本文所述對大家java程序設(shè)計有所幫助。
相關(guān)文章
Springboot如何統(tǒng)一處理Filter異常
這篇文章主要介紹了Springboot如何統(tǒng)一處理Filter異常問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2023-12-12Java中的String對象數(shù)據(jù)類型全面解析
首先String不屬于8種基本數(shù)據(jù)類型,String是一個對象,因為對象的默認值是null,所以String的默認值也是null;但它又是一種特殊的對象,有其它對象沒有的一些特性2012-11-11