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