在Java中,关闭父输入流也会关闭其子节点吗?

Oko*_*onX 8 java

FileInputStream fis = new FileInputStream(gzipFile);
GZIPInputStream gis = new GZIPInputStream(fis);
gis.close();
fis.close();
Run Code Online (Sandbox Code Playgroud)

fis.close()是否必要?虽然我正在运行此代码,但似乎没有任何错误.

ada*_*shr 8

你应该看到实现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;
    }
}
Run Code Online (Sandbox Code Playgroud)

如果你看一下构造函数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);
}
Run Code Online (Sandbox Code Playgroud)

观察变量in.注意它是如何传递给超类的,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;
    }
}
Run Code Online (Sandbox Code Playgroud)

显然,in.close()正在被召集.所以包裹(装饰)FileInputStream也在通话时关闭GZIPInputStream.close().这使得呼叫变得fis.close()多余.