BufferedOutputStream 源码分析

来源:互联网 发布:淘宝外贸男装店推荐 编辑:程序博客网 时间:2024/05/16 01:58
BufferedOutputStream实现了一个缓冲输出流。构建了这样一个输出流后,应用可以往底层流写数据而不用每次写一个字节都调用底层流的方法。 

Java代码  收藏代码
  1. public class BufferedOutputStream extends FilterOutputStream {  
  2.   
  3.     // 内部缓冲区,存储数据  
  4.     protected byte buf[];  
  5.   
  6.     // 缓冲区中有效的字节数(0 ~ buf.length)  
  7.     protected int count;  
  8.   
  9.     // 构造方法,创建一个新的输出缓冲流,并把数据写到指定的底层输出流  
  10.     public BufferedOutputStream(OutputStream out) {  
  11.         this(out, 8192);  
  12.     }  
  13.   
  14.     // 构造方法,创建一个新的输出缓冲流,以将具有指定缓冲区大小的数据写到指定的底层输出流。  
  15.     public BufferedOutputStream(OutputStream out, int size) {  
  16.         super(out);  
  17.         if (size <= 0) {  
  18.             throw new IllegalArgumentException("Buffer size <= 0");  
  19.         }  
  20.         buf = new byte[size];  
  21.     }  
  22.   
  23.     // 刷新内部的缓冲区,这会让内部缓冲区的有效字节被写出到此缓冲的输出流中  
  24.     private void flushBuffer() throws IOException {  
  25.         if (count > 0) {  
  26.             out.write(buf, 0, count);  
  27.             count = 0;  
  28.         }  
  29.     }  
  30.   
  31.     // 将指定的字节写入此缓冲的输出流  
  32.     public synchronized void write(int b) throws IOException {  
  33.         // 如果缓冲区满,则刷新缓冲区  
  34.         if (count >= buf.length) {  
  35.             flushBuffer();  
  36.         }  
  37.         buf[count++] = (byte)b;  
  38.     }  
  39.   
  40.     // 将指定字节数组中的从偏移量off开始len个字节写入此缓冲的输出流  
  41.     public synchronized void write(byte b[], int off, int len) throws IOException {  
  42.         if (len >= buf.length) {  
  43.             // 如果待写入的字节数大于或等于缓冲区大小,刷新缓冲区,并直接写入到输出流中  
  44.             flushBuffer();  
  45.             out.write(b, off, len);  
  46.             return;  
  47.         }  
  48.         if (len > buf.length - count) {  
  49.             flushBuffer();  
  50.         }  
  51.         System.arraycopy(b, off, buf, count, len);  
  52.         count += len;  
  53.     }  
  54.   
  55.     // 刷新此缓冲区和输出流,这会使所有缓冲的输出字节被写出到底层输出流中  
  56.     // 为了让缓冲区的数据能被写入到底层输出流中,可以显式调用该方法。或者调用close()方法(父类FilterOutputStream的close()方法),在close方法里,调用该flush()方法  
  57.     public synchronized void flush() throws IOException {  
  58.         flushBuffer();  
  59.         out.flush();  
  60.     }  
0 0
原创粉丝点击