2012-12-26 116 views
4
FileInputStream fstream = new FileInputStream(someFile.getPath()); 
DataInputStream in = new DataInputStream(fstream); 

如果我打電話給in.close(),它也會關閉fstream?我的代碼是給GC例外如下:關閉DataInputStream也會關閉FileInputStream嗎?

java.lang.OutOfMemoryError:GC開銷超過限制

回答

5

是,DataInputStream.close()也將關閉你的FileInputStream

+0

BufferedReader br = new BufferedReader(new InputStreamReader(in)); –

+0

我也有一個緩衝閱讀器,但我不會在最後關閉它可能會導致GC的開銷? –

+0

@Ady.Q如果你現在的問題是關於將BufferedReader.close()關閉InputStreamReader的話,答案也會是「是 - 它會的」。 – Andremoniy

4

DataOutputStream繼承了它從FilterOutputStreamclose() - 方法誰是documentation指出:

Closes this output stream and releases any system resources associated with the stream.

The close method of FilterOutputStream calls its flush method, and then calls the close method of its underlying output stream.

同樣應該是所有Writer -implementations真(雖然它不是在文檔中說明)。


爲了避免流在Java中工作時遇到了內存問題,使用這個模式:

// Just declare the reader/streams, don't open or initialize them! 
BufferedReader in = null; 
try { 
    // Now, initialize them: 
    in = new BufferedReader(new InputStreamReader(in)); 
    // 
    // ... Do your work 
} finally { 
    // Close the Streams here! 
    if (in != null){ 
     try { 
      in.close(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
    } 
} 

這看起來不太凌亂與Java7,因爲它引入了AutoCloseable-interface,這是所有的流執行/作家/讀者類。請參閱tutorial