首页 > 学院 > 开发设计 > 正文

BufferedOutputStream

2019-11-06 06:43:52
字体:
来源:转载
供稿:网友
public class BufferedOutputStream extends FilterOutputStream { PRotected byte buf[]; protected int count; //Creates a new buffered output stream to write data to the specified 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 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);//out 属于 FilterOutputStream count = 0; } } // write(int b)省略不敲了...... 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; } public synchronized void flush() throws IOException { flushBuffer(); out.flush(); }}
继承关系 根本上,BufferedOutputStream是OutputStream的子类。其定义的变量 两个用protected修饰的buf( The internal buffer where data is stored.内部缓冲区) 和count(The number of valid bytes in the buffer. This value is always in the range 0 through buf.length. 类似于一个计数器) (为什么不像String一样,用private修饰呢?protected是表明有子类继承并使用该变量吗?)构造器1 param:OutputStream,其调用另一个构造器,传递的参数为out和常数8192构造器2 param:OutputStream,int , 其为父类中的out赋值,并且实例化内部缓冲区方法:flushBuffer( ) 清空缓冲区,并将count清零方法:write(byte[] b, int offset, int len) 这个方法被synchronized修饰,同步 。 该方法是将一个数组写入文件,传入的参数为要写入的数组,开始读取数组的位置及读取的长度 假设两个if都不成立,即缓冲区没有满,则执行: System.arraycopy(b, off, buf, count, len); count += len; 将数组内容添加到buf中(count的作用:控制添加外来数组的位置)方法:flush( ) 该方法也被synchronized修饰,”ren”可以主动清空缓冲区(即使内部缓冲区没有满)。
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表