Java中字節緩沖流的原理是什么?針對這個問題,這篇文章詳細介紹了相對應的分析和解答,希望可以幫助更多想解決這個問題的小伙伴找到更簡單易行的方法。
1.SpringMVC,Spring Web MVC是一種基于Java的實現了Web MVC設計模式的請求驅動類型的輕量級Web框架。2.Shiro,Apache Shiro是Java的一個安全框架。3.Mybatis,MyBatis 是支持普通 SQL查詢,存儲過程和高級映射的優秀持久層框架。4.Dubbo,Dubbo是一個分布式服務框架。5.Maven,Maven是個項目管理和構建自動化工具。6.RabbitMQ,RabbitMQ是用Erlang實現的一個高并發高可靠AMQP消息隊列服務器。7.Ehcache,EhCache 是一個純Java的進程內緩存框架。
一 介紹
BufferInputStresm和BufferOutputStream
這兩個流類為IO提供了帶緩沖區的操作,一般打開文件進行寫入或讀取操作時,都會加上緩沖,這種流模式提高了IO的性能。
二 各類中方法比較
從應用程序中把輸入放入文件,相當于將一缸水倒入另外一個缸中:
FileOutputStream的write方法:相當于一滴一滴地把水“轉移過去。
DataOutputStream的writeXXX方法:相當于一瓢一瓢地把水轉移過去。
BufferOutputStream的write方法:相當于一瓢一瓢先把水放入的桶中,再將桶中的水倒入缸中,性能提高了。
三 應用——帶緩沖區的拷貝
/** * 進行文件的拷貝,利用帶緩沖的字節流 * @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();//刷新緩沖區 } bis.close(); bos.close(); }
四 應用——單字節,不帶緩沖的拷貝
/** * 單字節,不帶緩沖進行文件拷貝 * @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(); } } }
六 測試結果
13091
9067
10
關于Java中字節緩沖流的原理是什么問題的解答就分享到這里了,希望以上內容可以對大家有一定的幫助,如果你還有很多疑惑沒有解開,可以關注億速云行業資訊頻道了解更多相關知識。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。