Welcome 微信登录

首页 / 软件开发 / JAVA / java io学习(十二) BufferedOutputStream的认知、源码和示例

java io学习(十二) BufferedOutputStream的认知、源码和示例2014-08-12BufferedOutputStream(缓冲输出流)的认知、源码和示例

本章内容包括3个部分:BufferedOutputStream介绍,BufferedOutputStream源码,以及BufferedOutputStream使用示例。

BufferedOutputStream 介绍

BufferedOutputStream 是缓冲输出流。它继承于FilterOutputStream。

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

BufferedOutputStream 函数列表

BufferedOutputStream(OutputStream out)BufferedOutputStream(OutputStream out, int size) synchronized void close()synchronized void flush()synchronized void write(byte[] buffer, int offset, int length)synchronized void write(int oneByte)
BufferedOutputStream 源码分析(基于jdk1.7.40)

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