当我关闭BufferedInputStream时,底层的InputStream是否也关闭了?

时间:2014-06-23 09:51:59

标签: java inputstream bufferedinputstream

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()来关闭?

5 个答案:

答案 0 :(得分:25)

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

所以答案是:是

答案 1 :(得分:6)

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

答案 2 :(得分:4)

当您关闭BufferedInputStream时,底层的InputStream确实也已关闭。 :)

答案 3 :(得分:2)

是。基础流将被关闭。

答案 4 :(得分:2)

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

因此,流将被关闭