JDK1.8源码学习--io包(BufferedOutputStream)

前言
 

月是一轮明镜,晶莹剔透,代表着一张白纸(啥也不懂)

央是一片海洋,海乃百川,代表着一块海绵(吸纳万物)

泽是一柄利剑,千锤百炼,代表着千百锤炼(输入输出)

月央泽,学习的一种过程,从白纸->吸收各种知识->不断输入输出变成自己的内容

希望大家一起坚持这个过程,也同样希望大家最终都能从零到零,把知识从薄变厚,再由厚变薄!
 

一.BufferedOutputStream的作用:


         直接看源码注释(我的翻译可能不太准,如果道友们有更棒的理解,可以留言或者私信)

/**
 * The class implements a buffered output stream. By setting up such
 * an output stream, an application can write bytes to the underlying
 * output stream without necessarily causing a call to the underlying
 * system for each byte written.
 * 该类实现了一个缓冲输出流。通过设置这样的输出流,应用程序可以将字节写入底层输出流,
 * 而不必为写入的每个字节调用底层系统
 * @author  Arthur van Hoff
 * @since   JDK1.0
 */


二.类图:

三.成员变量: 

    /**
     * 存储数据的内部缓冲区。
     */
    protected byte buf[];

    /**
     * 缓冲区中的有效字节数。这个值总是在0到buf.length的范围内;
     * 元素buf[0]到buf[count-1]包含有效的字节数据
     */
    protected int count;

四.构造方法: 

    /**
     * 创建一个新的缓冲输出流以将数据写入指定的底层输出流
     */
    public BufferedOutputStream(OutputStream out) {
        this(out, 8192);
    }

    /**
     * 创建一个新的缓冲输出流,以将数据写入具有指定缓冲区大小的指定底层输出流。
     */
    public BufferedOutputStream(OutputStream out, int size) {
        super(out);
        if (size <= 0) {
            throw new IllegalArgumentException("Buffer size <= 0");
        }
        buf = new byte[size];
    }

五.内部方法:

                write

    /**
     * 将指定字节写入此缓冲输出流
     */
    public synchronized void write(int b) throws IOException {
        if (count >= buf.length) {
            flushBuffer();
        }
        buf[count++] = (byte)b;
    }

    /**
     * 1.将len字节从从偏移量off开始的指定字节数组写入此缓冲输出流
     * 2.通常,此方法将给定数组中的字节存储到此流的缓冲区中,根据需要将缓冲区刷新到底层输出流。
     * 但是,如果请求的长度至少与此流的缓冲区一样大,则此方法将刷新缓冲区并将字节直接写入底层输出流。
     * 因此冗余的BufferedOutputStream (s) 不会不必要地复制数据
     */
    public synchronized void write(byte b[], int off, int len) throws IOException {
        if (len >= buf.length) {
            /* If the request length exceeds the size of the output buffer,
               flush the output buffer and then write the data directly.
               In this way buffered streams will cascade harmlessly. */
            //如果请求长度超过输出缓冲区的大小,则刷新输出缓冲区,然后直接写入数据。这样缓冲的流将无害地级联
            flushBuffer();
            out.write(b, off, len);
            return;
        }
        if (len > buf.length - count) {
            flushBuffer();
        }
        System.arraycopy(b, off, buf, count, len);
        count += len;
    }

                flush

   /**
     * 刷新这个缓冲的输出流。这会强制将任何缓冲的输出字节写出到基础输出流。
     */
    public synchronized void flush() throws IOException {
        flushBuffer();
        out.flush();
    }

六.总结:

        缓存输出流,java中很多地方都有利用缓存的思想...

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值