BufferedOutputStream(緩衝輸出資料流)的認知、源碼和樣本
本章內容包括3個部分:BufferedOutputStream介紹,BufferedOutputStream源碼,以及BufferedOutputStream使用樣本。
BufferedOutputStream 介紹
BufferedOutputStream 是緩衝輸出資料流。它繼承於FilterOutputStream。
BufferedOutputStream 的作用是為另一個輸出資料流提供“緩衝功能”。
BufferedOutputStream 函數列表
BufferedOutputStream(OutputStream out)BufferedOutputStream(OutputStream out, int size) synchronized void close()synchronized void flush()synchronized void write(byte[] buffer, int offset, int length)synchronized void write(int oneByte)
BufferedOutputStream 源碼分析(基於jdk1.7.40)
package java.io; public class BufferedOutputStream extends FilterOutputStream { // 儲存“緩衝輸出資料流”資料的位元組數組 protected byte buf[]; // 緩衝中資料的大小 protected int count; // 建構函式:建立位元組數組大小為8192的“緩衝輸出資料流” public BufferedOutputStream(OutputStream out) { this(out, 8192); } // 建構函式:建立位元組數組大小為size的“緩衝輸出資料流” public BufferedOutputStream(OutputStream out, int size) { super(out); if (size <= 0) { throw new IllegalArgumentException("Buffer size <= 0"); } buf = new byte[size]; } // 將緩衝資料都寫入到輸出資料流中 private void flushBuffer() throws IOException { if (count > 0) { out.write(buf, 0, count); count = 0; } } // 將“資料b(轉換成位元組類型)”寫入到輸出資料流中 public synchronized void write(int b) throws IOException { // 若緩衝已滿,則先將緩衝資料寫入到輸出資料流中。 if (count >= buf.length) { flushBuffer(); } // 將“資料b”寫入到緩衝中 buf[count++] = (byte)b; } public synchronized void write(byte b[], int off, int len) throws IOException { // 若“寫入長度”大於“緩衝區大小”,則先將緩衝中的資料寫入到輸出資料流,然後直接將數組b寫入到輸出資料流中 if (len >= buf.length) { flushBuffer(); out.write(b, off, len); return; } // 若“剩餘的緩衝空間 不足以 儲存即將寫入的資料”,則先將緩衝中的資料寫入到輸出資料流中 if (len > buf.length - count) { flushBuffer(); } System.arraycopy(b, off, buf, count, len); count += len; } // 將“緩衝資料”寫入到輸出資料流中 public synchronized void flush() throws IOException { flushBuffer(); out.flush(); }}
說明:
BufferedOutputStream的源碼非常簡單,這裡就BufferedOutputStream的思想進行簡單說明:BufferedOutputStream通過位元組數組來緩衝資料,當緩衝區滿或者使用者調用flush()函數時,它就會將緩衝區的資料寫入到輸出資料流中。
查看本欄目更多精彩內容:http://www.bianceng.cnhttp://www.bianceng.cn/Programming/Java/