【问题标题】:When I close a BufferedInputStream, is the underlying InputStream also closed? [duplicate]当我关闭 BufferedInputStream 时,底层 InputStream 是否也关闭了? [复制]
【发布时间】:2014-08-13 07:40:06
【问题描述】:
InputStream in = SomeClass.getInputStream(...);
BufferedInputStream bis = new BufferedInputStream(in);

try {
    // read data from bis
} finally {
    bis.close();
    in.close();    
}

BufferedInputStream.close() 的 javadoc 没有提及底层流是否关闭:

关闭此输入流并释放所有关联的系统资源 与流。一旦流被关闭,进一步读取(), available()、reset() 或 skip() 调用将引发 IOException。 关闭之前关闭的流没有任何效果。

显式调用in.close() 是必要的,还是应该通过调用bis.close() 来关闭它?

【问题讨论】:

标签: java inputstream bufferedinputstream


【解决方案1】:

BufferedInputStream 本身不保存任何系统资源;它只是包装了一个保存这些资源的 InputStream。因此 BufferedInputStream 将关闭操作转发到被包装的 InputStream 上,然后它将释放其资源。

【讨论】:

    【解决方案2】:

    来自BufferedInputStream的源码:

    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()
        }
    }
    

    所以答案是:是的

    【讨论】:

      【解决方案3】:

      这是Java实现

      /**
       * Closes this input stream and releases any system resources
       * associated with the stream.
       * Once the stream has been closed, further read(), available(), reset(),
       * or skip() invocations will throw an IOException.
       * Closing a previously closed stream has no effect.
       *
       * @exception  IOException  if an I/O error occurs.
       */
      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()
          }
      }
      

      所以,流将被关闭

      【讨论】:

        【解决方案4】:

        是的。底层流将被关闭。

        【讨论】:

          【解决方案5】:

          当你关闭一个 BufferedInputStream 时,底层的 InputStream 确实也被关闭了。 :)

          【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2010-11-28
          • 2015-11-17
          • 2012-03-23
          • 2010-12-18
          • 2016-02-26
          • 2023-03-06
          • 2012-04-06
          • 2019-01-20
          相关资源
          最近更新 更多