public class BufferedOutputStream extends FilterOutputStream { PRotected byte buf[]; protected int count; //Creates a new buffered output stream to write data to the specified underlying output stream public BufferedOutputStream(OutputStream out) { this(out, 8192); } //Creates a new buffered output stream to write data to the specified underlying output stream with the specified buffer 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);//out 屬于 FilterOutputStream count = 0; } } // write(int b)省略不敲了...... public synchronized void write(byte[] b, int off, int len) throws IOException { 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是OutputStream的子類。其定義的變量 兩個用protected修飾的buf( The internal buffer where data is stored.內部緩沖區(qū)) 和count(The number of valid bytes in the buffer. This value is always in the range 0 through buf.length. 類似于一個計數器) (為什么不像String一樣,用private修飾呢?protected是表明有子類繼承并使用該變量嗎?)構造器1 param:OutputStream,其調用另一個構造器,傳遞的參數為out和常數8192構造器2 param:OutputStream,int , 其為父類中的out賦值,并且實例化內部緩沖區(qū)方法:flushBuffer( ) 清空緩沖區(qū),并將count清零方法:write(byte[] b, int offset, int len) 這個方法被synchronized修飾,同步 。 該方法是將一個數組寫入文件,傳入的參數為要寫入的數組,開始讀取數組的位置及讀取的長度 假設兩個if都不成立,即緩沖區(qū)沒有滿,則執(zhí)行: System.arraycopy(b, off, buf, count, len); count += len; 將數組內容添加到buf中(count的作用:控制添加外來數組的位置)方法:flush( ) 該方法也被synchronized修飾,”ren”可以主動清空緩沖區(qū)(即使內部緩沖區(qū)沒有滿)。