gpt4 book ai didi

java - 在 Java 中,关闭父输入流是否也会关闭其子输入流?

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:40:41 26 4
gpt4 key购买 nike

FileInputStream fis = new FileInputStream(gzipFile);
GZIPInputStream gis = new GZIPInputStream(fis);
gis.close();
fis.close();

fis.close() 是必要的吗?虽然我正在运行这段代码,但似乎没有出现任何错误。

最佳答案

您应该看到 GZIPInputStream.close() 的实现。

/**
* Closes this input stream and releases any system resources associated
* with the stream.
* @exception IOException if an I/O error has occurred
*/
public void close() throws IOException {
if (!closed) {
super.close();
eos = true;
closed = true;
}
}

如果您看一下 GZIPInputStream 的构造函数,它看起来像这样:

/**
* Creates a new input stream with the specified buffer size.
* @param in the input stream
* @param size the input buffer size
* @exception IOException if an I/O error has occurred
* @exception IllegalArgumentException if size is <= 0
*/
public GZIPInputStream(InputStream in, int size) throws IOException {
super(in, new Inflater(true), size);
usesDefaultInflater = true;
readHeader(in);
}

观察变量in。请注意它是如何传递给父类(super class)的,在本例中为 InflaterInputStream

现在,如果我们看一下 InflaterInputStream.close() 方法的实现,我们会发现:

/**
* Closes this input stream and releases any system resources associated
* with the stream.
* @exception IOException if an I/O error has occurred
*/
public void close() throws IOException {
if (!closed) {
if (usesDefaultInflater)
inf.end();
in.close();
closed = true;
}
}

很明显,正在调用 in.close()。因此,包装(装饰)FileInputStream 也会在调用 GZIPInputStream.close() 时关闭。这使得调用 fis.close() 变得多余。

关于java - 在 Java 中,关闭父输入流是否也会关闭其子输入流?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8984303/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com