BufferedOutputStream 源码分析

本文介绍了BufferedOutputStream类的实现原理及使用方法。该类通过字节数组缓冲数据,在缓冲区满或调用flush()方法时,将数据写入底层输出流。文章详细解释了构造函数、write()和flush()等方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

转自:

BufferedOutputStream 是缓冲输出流。它继承于FilterOutputStream。
BufferedOutputStream 的作用是为另一个输出流提供“缓冲功能”。

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()函数时,它就会将缓冲区的数据写入到输出流中。



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值