首页 > 代码库 > java.io.BufferedOutputStream 源码分析

java.io.BufferedOutputStream 源码分析

BufferedOutputStream  是一个带缓冲区到输出流,通过设置这种输出流,应用程序就可以将各个字节写入底层输出流中,而不必针对每次字节写入调用底层系统。

俩个成员变量,一个是存储数据的内部缓冲区,一个是缓冲区中的有效字节数。

 

    /**
     * The internal buffer where data is stored.
     */
    protected byte buf[];

    /**
     * The number of valid bytes in the buffer. This value is always
     * in the range <tt>0</tt> through <tt>buf.length</tt>; elements
     * <tt>buf[0]</tt> through <tt>buf[count-1]</tt> contain valid
     * byte data.
     */
    protected int count;

 

 

构造参数可以使用默认大小,也可以指定大小。

    /**
     * Creates a new buffered output stream to write data to the
     * specified underlying output stream.
     *
     * @param   out   the 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.
     *
     * @param   out    the underlying output stream.
     * @param   size   the buffer size.
     * @exception IllegalArgumentException if size &lt;= 0.
     */
    public BufferedOutputStream(OutputStream out, int size) {
        super(out);
        if (size <= 0) {
            throw new IllegalArgumentException("Buffer size <= 0");
        }
        buf = new byte[size];
    }

 

 

刷新缓冲区数据到底层输出流。

 

 /** Flush the internal buffer */
    private void flushBuffer() throws IOException {
        if (count > 0) {
            out.write(buf, 0, count);
            count = 0;
        }
    }

 

 

输出一个字节。

    public synchronized void write(int b) throws IOException {
     //判断缓冲区字节数如果大于缓冲区到长度就刷新缓冲区
if (count >= buf.length) { flushBuffer(); } buf[count++] = (byte)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();
    }