Java-----IO流【字节缓冲输出、输入流】
生活随笔
收集整理的這篇文章主要介紹了
Java-----IO流【字节缓冲输出、输入流】
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
字節緩沖輸出流
概述
-
緩沖流,也叫高效流,是對4個基本都FileXxx流的增強,所以也是4個流,按照數據類型分類:
- 字節緩沖流:BufferedInputStream,BufferedOutputStream
- 字符緩沖流:BufferedReader,BufferedWriter
緩沖流的基本原理,是在創建流對象時,會創建一個內置的默認大小的緩沖區數組,通過緩沖區讀寫,減少系統IO次數,從而提高讀寫的效率。
構造方法(字節緩沖流)
- public BufferedInputStream(InputStream in):創建一個 新的緩沖輸入流
- public BufferedOutputStream(OutputStream out):創建一個新的緩沖輸出流。
字節緩沖輸出流
-
實例:
public static void main(String[] args) throws Exception{// FileInputStream和BufferedInputStream都是繼承InputStream類的OutputStream out = new BufferedOutputStream(new FileOutputStream("a.txt"));out.write("Hello Worl\r\n".getBytes());// 并沒有直接寫入到文件,寫入到內存中的一個緩沖區out.write("Hello Worl\r\n".getBytes());out.flush();// 手動刷新緩沖區數據到硬盤文件// 但假如說 還沒執行到close,緩沖區已經有超過1G的文件還沒有寫入,那怎么辦呢?out.write("Hello Worlr\r\n".getBytes());// 調用close()方法的時候,會先將緩沖區中的內容刷新到硬盤的目標文件中,然后關閉流out.close();}
字節緩沖輸入流
-
實例:
// 讀取文件內容到內存 public static void main(String[] args) throws IOException{InputStream in = new BufferedInputStream(new FileInputStream("a.txt"));byte[] bytes = new byte[1024];int len = 0;while((len = in.read(bytes))!=-1){System.out.println(new String(bytes,0,len));}in.close(); }
使用字節緩沖流復制文件
public static void main(String[] args) throws Exception{long l = System.currentTimeMillis();// 字節流可以輕松復制圖片和視頻文件到其他文件夾中,但是用于傳輸文本文檔內容可能會有亂碼// 創建一個讀取文件的字節輸入流InputStream is = new FileInputStream("D://b站視頻下載//【震我一下魔方宅】五階魔方基礎還原教程//mfjc.mp4");// 創建一個寫入硬盤數據的字節輸出流OutputStream os = new FileOutputStream("D://b站視頻下載//mfjc.mp4");byte[] b = new byte[1024];int len = 0;while ((len = is.read(b)) != -1){os.write(b,0,len);}os.close();is.close();long l2 = System.currentTimeMillis();System.out.println("用時:"+(l+l2)/1000+"秒");} public static void main(String[] args) throws Exception{long l1 = System.currentTimeMillis();InputStream in = new BufferedInputStream(new FileInputStream("D://b站視頻下載//【震我一下魔方宅】五階魔方基礎還原教程//mfjc.mp4"));OutputStream ou = new BufferedOutputStream(new FileOutputStream("D://b站視頻下載//mfjc.mp4"));byte[] b = new byte[1024];int len = 0;while((len = in.read(b)) != -1){ou.write(b,0,len);}ou.close();in.close();long l2 = System.currentTimeMillis();System.out.println((l1+l2)/1000);} // 用時:3233098217秒 // 3233098902// 緩沖流用時長總結
以上是生活随笔為你收集整理的Java-----IO流【字节缓冲输出、输入流】的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 2021年中国智慧医疗行业白皮书 附下载
- 下一篇: java白皮书是什么_Java SE 参