Java IO包裝流如何關閉

Java IO包裝流如何關閉

一、JAVA的IO流使用了裝飾模式,關閉最外面的流的時候會自動調用被包裝的流的close()方法?
二、若是按順序關閉流,是從內層流到外層流關閉仍是從外層到內存關閉?java

BufferedInputStream.close()方法this

public void close() throws IOException {
      byte[] buffer;
      while ( (buffer = buf) != null) {
          if (bufUpdater.compareAndSet(this, buffer, null)) {
              InputStream input = in;
              in = null;
              if (input != null)
                  input.close();
              return;
          }
          // Else retry in case a new buf was CASed in fill()
      }
  }

能夠上述代碼能夠看出,BufferedInputStream.close()方法調用了input.close()方法。code

JAVA的IO流使用了裝飾模式,關閉最外面的流的時候會自動調用被包裝的流的close()方法。內存

  • 通常狀況下是:先打開的後關閉,後打開的先關閉。
  • 另外一種狀況:看依賴關係,若是流a依賴流b,應該先關閉流a,再關閉流b, 固然徹底能夠只關閉處理流,不用關閉節點流。處理流關閉的時候,會調用其處理的節點流的關閉方法
相關文章
相關標籤/搜索