2012-12-26 72 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