FileInputStream fstream = new FileInputStream(someFile.getPath());
DataInputStream in = new DataInputStream(fstream);
如果我呼叫in.close()
,也会关闭fstream
吗?我的代码给出了GC异常,如下所示:
java.lang.OutOfMemoryError:超出了GC开销限制
是,DataInputStream.close()
也会关闭您的FileInputStream
。
这是因为DataInputStream
继承了FilterInputStream
,它具有close()
方法的以下实现:
public void close() throws IOException {
in.close();
}
您的DataOutputStream
继承自close()
指出的FilterOutputStream
方法:[]
关闭此输出流,并释放任何系统资源与流关联。
FilterOutputStream的close方法调用其flush方法,然后然后调用其基础输出流的close方法。
对于所有documentation实现都应如此(尽管文档中未作说明)。>>
为了避免在Java中使用Streams时遇到内存问题,请使用以下模式:
Writer
这对Java7看起来不那么混乱,因为它引入了
// 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(); } } }
,它由所有Stream / Writer / Reader类实现。参见AutoCloseable
-interface。