首先要明確一個概念:java
對文件或其餘目標頻繁的讀寫操做,效率低,性能差。數組
使用緩衝流的好處是:可以高效的讀寫信息,原理是先將數據先緩衝起來,而後一塊兒寫入或者讀取出來。緩存
對於字節:性能
BufferedInputStream:爲另外一個輸入流添加一些功能,在建立BufferedInputStream時,會建立一個內部緩衝區數組,用於緩衝數據。spa
BufferedOutputStream:經過設置這種輸出流,應用程序就能夠將各個字節寫入底層輸出流中,而沒必要針對每次字節寫入調用底層系統。code
對於字符:blog
BufferedReader:將字符輸入流中讀取文本,並緩衝各個字符,從而實現字符、數組、和行的高效讀取。字符串
BufferedWriter:將文本寫入字符輸出流,緩衝各個字符,從而提供單個字符、數組和字符串的高效寫入。get
代碼示例:it
package IODemo; import java.io.*; /* 緩衝的目的: 解決在寫入文件操做時,頻繁的操做文件所帶來的性能下降的問題 BufferedOutStream 內部默認的緩衝大小是 8Kb,每次寫入儲存到緩存中的byte數組中,當數組存盡是,會把數組中的數據寫入文件 而且緩存下標歸零 */ public class BufferedDemo { //使用新語法 會在try裏面幫關掉這個流 private static void BuffRead2(){ File file = new File("d:\\test\\t.txt"); try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file))){ byte[] bytes = new byte[1024]; int len = -1; while ((len = bis.read(bytes))!=-1){ System.out.println(new String(bytes,0,len)); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } private static void BuffRead(){ File file = new File("d:\\test\\t.txt"); try { InputStream in = new FileInputStream(file); BufferedInputStream bis = new BufferedInputStream(in); byte[] bytes = new byte[1024]; int len = -1; while ((len = bis.read(bytes))!=-1){ System.out.println(new String(bytes,0,len)); } bis.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } private static void BuffWrite(){ File file = new File("d:\\test\\t.txt"); try { OutputStream out = new FileOutputStream(file); //構造一個字節緩衝流 BufferedOutputStream bos = new BufferedOutputStream(out); String info = "我是落魄書生"; bos.write(info.getBytes()); bos.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } public static void main(String[] args) { // BuffWrite(); BuffRead2(); } }