关闭Reader后,是否需要关闭InputStream? [英] Do I need to close InputStream after I close the Reader
问题描述
我想知道,在我关闭阅读器之后是否需要关闭InputStream?
I was wondering, whether is there any need for me to close the InputStream, after I close the reader?
try {
inputStream = new java.io.FileInputStream(file);
reader = new InputStreamReader(inputStream, Charset.forName("UTF-8"));
}
catch (Exception exp) {
log.error(null, exp);
}
finally {
if (false == close(reader)) {
return null;
}
// Do I need to close inputStream as well?
if (false == close(inputStream)) {
return null;
}
}
推荐答案
否,你不必这么做。
由于用于Java中的流的装饰器方法可以通过将它们附加到其他流来构建新的流或读取器,因此将自动处理通过 InputStreamReader
实现。
Since the decorator approach used for streams in Java can build up new streams or reader by attaching them on others this will be automatically be handled by InputStreamReader
implementation.
如果查看其源 InputStreamReader.java
你看到了:
If you look at its source InputStreamReader.java
you see that:
private final StreamDecoder sd;
public InputStreamReader(InputStream in) {
...
sd = StreamDecoder.forInputStreamReader(in, this, (String)null);
...
}
public void close() throws IOException {
sd.close();
}
因此,关闭操作实际上会关闭 InputStream
是基础读取器的基础。
So the close operation actually closes the InputStream
underlying the stream reader.
编辑:我想确保 StreamDecoder
关闭也适用于输入流,请继续关注。
I wanna be sure that StreamDecoder
close works also on input stream, stay tuned.
选中 StreamDecoder.java
void implClose() throws IOException {
if (ch != null)
ch.close();
else
in.close();
}
在调用sd关闭时调用。
which is called when sd's close is called.
这篇关于关闭Reader后,是否需要关闭InputStream?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!