继承和导入关系:
BufferedOutputStream类继承自FilterOutputStream类
BufferedOutputStream类和上篇博客所讲到BufferedInputStream类有着类似的功能,还是常规,先来分析一下关于该类的注释:
/** * 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 */
比BufferedInputStream的注释看着少了很多,功能和代码量也相对应的少了许多。
注释的大意如下:
这个类是一个缓冲输出流的接口
通过设置一个这样的输出流
一个应用程序可以向类内封装的输出流写入byte类型的数据且不必通过调用系统底层功能去操作每一个byte数据
BufferedOutputStream类含有如下的变量:
缓冲区数组:
protected byte buf[];
数组中有效数据长度:
protected int count;
BufferedOutputStream类含有如下的方法:
构造方法(构造默认大小的缓冲数组):
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]; }
将缓冲数组中的数据写入输出流中:
private void flushBuffer() throws IOException { if (count > 0) { out.write(buf, 0, count); count = 0; } }
flushBuffer的上层函数,首先判定当前有效值是否已经超出缓冲数组最大值,如果超过则通过调用flushBuffer将缓冲数组中的数据写入输出流,然后重置缓冲数组并向数组中写入数据,否则直接向缓冲数组中写入数据:
public synchronized void write(int b) throws IOException { if (count >= buf.length) { flushBuffer(); } buf[count++] = (byte)b; }
上个write函数的重载,直接一次性写入一个数组。当需写入数组长度大与缓冲区长度时,先将缓冲区的数据写入输出流,然后将该写入数组不经缓冲区直接写入输出流。若写入数组长度大于当前缓冲区剩余长度且小于缓冲区长度时,将缓冲区数据写出并重置,然后将该数组置入缓冲区。若写入数组长度小于当前缓冲区剩余长度则直接置入缓冲区:
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; }
将输出流内东西输出。先将自身缓冲区内数据写入输出流,然后将输出流内数据向目标文件写出:
public synchronized void flush() throws IOException { flushBuffer(); out.flush(); }
相对于缓冲输入流,缓冲输出流的结构非常简单,功能也十分明确。
1104



被折叠的 条评论
为什么被折叠?



