这个问题在这里已有答案:
InputStream in = SomeClass.getInputStream(...);
BufferedInputStream bis = new BufferedInputStream(in);
try {
// read data from bis
} finally {
bis.close();
in.close();
}
BufferedInputStream.close()
的javadoc未提及底层流是否已关闭:
关闭此输入流并释放与该流关联的所有系统资源。关闭流后,进一步的read(),available(),reset()或skip()调用将抛出IOException。关闭先前关闭的流无效。
是否必须明确调用in.close()
,还是应该通过调用bis.close()
来关闭它?
来自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()
}
}
所以答案是:是的
BufferedInputStream本身不包含任何系统资源;它只是包含一个保存这些资源的InputStream。因此,BufferedInputStream将关闭操作转发到包装的InputStream,然后将释放其资源。
当您关闭BufferedInputStream时,基础InputStream确实也已关闭。 :)
是。底层流将被关闭。
这是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()
}
}
因此,流将被关闭