首页 > 编程语言 > 详细

java.io.BufferedOutputStream 源码分析

时间:2014-06-11 22:59:55      阅读:491      评论:0      收藏:0      [点我收藏+]

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

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

 

bubuko.com,布布扣
    /**
     * 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;
bubuko.com,布布扣

 

 

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

bubuko.com,布布扣
    /**
     * 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];
    }
bubuko.com,布布扣

 

 

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

 

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

 

 

输出一个字节。

bubuko.com,布布扣
    public synchronized void write(int b) throws IOException {
     //判断缓冲区字节数如果大于缓冲区到长度就刷新缓冲区
if (count >= buf.length) { flushBuffer(); } buf[count++] = (byte)b; }
bubuko.com,布布扣

 

输出多个字节

bubuko.com,布布扣
    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;
    }
bubuko.com,布布扣

 

刷新输出流,将缓冲区到字节输出到底层流当中

    public synchronized void flush() throws IOException {
        flushBuffer();
        out.flush();
    }

 

java.io.BufferedOutputStream 源码分析,布布扣,bubuko.com

java.io.BufferedOutputStream 源码分析

原文:http://www.cnblogs.com/daxin/p/3772278.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!