ByteArrayOutputStream.flush (求大神提意见)

 疑惑:

         在对内存流做控制的时候  发现了一个问题  就是 flush 方法  。  

         看继承 public class ByteArrayOutputStream extends OutputStream   和      BufferedOutputStream 一样 都是继承 OutputStream  这个抽象类   改抽象类 提供了 一个写入流到字节数组 的  write 方法

 

                 

  public void write(byte b[], int off, int len) throws IOException {
          if (b == null) {
            throw new NullPointerException();
        } else if ((off < 0) || (off > b.length) || (len < 0) ||
                   ((off + len) > b.length) || ((off + len) < 0)) {
            throw new IndexOutOfBoundsException();
        } else if (len == 0) {
            return;
        }
        for (int i = 0 ; i < len ; i++) {
            write(b[off + i]);
        }
    }

  

         还有一个空的 flush 方法。空的 flush 方法。空的 flush 方法。 说三遍啊! 

 

     public void flush() throws IOException {  }

    然后再看   子类  也就是   ByteArrayOutputStream   的 flush   当前类没有找到该方法, 说明子类没有重写 父类方法   所以  说  还是调用的 父类 OutputStream 的flush   也就是 空方法

      找不到问题 就对比者来    来看 BufferedOutputStream  类  

     

       public  class BufferedOutputStream extends FilterOutputStream    FilterOutputStream     extends  OutputStream    间接 继承 OutputStream   抽象类

       从上往下看    FilterOutputStream      类   

       FilterOutputStream      flush  调用父类的  OutputStream 的  flush 方法

     public void flush() throws IOException {
        out.flush();
    }

   接着 

       BufferedOutputStream   flush  

      BufferedOutputStream    重写了  flush 方法 并且加锁  调用了一个   flushBuffer 方法 

    public synchronized void flush() throws IOException {
        flushBuffer();
        out.flush();
     }

  

 

       来看    flushBuffer 方法 

       将  当前字节数组 放入了  out 参数的 的数组字段中。  out  是 new 的时候 需要传递过来的 

   private void flushBuffer() throws IOException {
        if (count > 0) {
            out.write(buf, 0, count);
            count = 0;
        }
    }

  关键就是  write   流对象调用 flush 目的是 将当前的 字节数组 传递给 上级流对象   上级流 本身就是最初的 数据源     flush 无上级 流对象  所以就是个空  

    

     蛋疼。。。  求详解。 

        

    

          

 

         

         

posted @ 2015-09-25 16:43  atliwen  阅读(3013)  评论(0)    收藏  举报