簡體   English   中英

在Java中,關閉父輸入流也會關閉其子節點嗎?

[英]In Java, does closing a parent input stream close its child, too?

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 注意在這種情況下如何將它傳遞給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() 因此,在調用GZIPInputStream.close()也會關閉包裝(修飾)的FileInputStream Thich使調用fis.close()變得多余。

這是人們需要清楚記錄的事情之一。 不幸的是, GZIPInputStream會覆蓋其父類中的close ,並且不會記錄它的作用(文檔很差)。 但是幾率很高(即使沒有查看代碼)它最終會調用super.close() (事實上​​我們可以從adarshr的答案看到它確實如此,盡管你永遠不應該假設實現不會改變)。 如果是這樣,那么我們查看父類( InflaterInputStream )的文檔。 不幸的是,它完全相同的事情,覆蓋沒有記錄。 但是假設它在某些時候也調用了super.close() 查看它的父類( FilterInputStream )文檔,它明確表示它對in成員close ,它是通過構造函數設置的。 (另一個假設是GZIPInputStreamInflaterInputStream將構造函數參數傳遞給它們的超類,但這很可能確實存在。)

所以FilterInputStream清楚地告訴你它將關閉你提供給構造函數的流。 其他人稱之為super.close()的可能性非常高,即使他們記錄不好,所以是的,它應該為你關閉它,你不應該自己做。 但是有一些假設涉及。

是的,它確實。 javadoc說:

關閉此輸入流並釋放與該流關聯的所有系統資源。

包裹的流肯定是這樣的系統資源。

而且,GZIPInputStream 是一個 FilterInputStream,FilterInputStream的javadoc說:

關閉此輸入流並釋放與該流關聯的所有系統資源。 此方法只執行in.close()。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM