FileInputStream fstream = new FileInputStream(someFile.getPath());
DataInputStream in = new DataInputStream(fstream);
如果我调用in.close()
,它会同时关闭fstream
吗?我的代码出现了以下GC异常:
java.lang.OutOfMemoryError: GC overhead limit exceeded
FileInputStream fstream = new FileInputStream(someFile.getPath());
DataInputStream in = new DataInputStream(fstream);
如果我调用in.close()
,它会同时关闭fstream
吗?我的代码出现了以下GC异常:
java.lang.OutOfMemoryError: GC overhead limit exceeded
是的,DataInputStream.close()
方法也会关闭你的FileInputStream
。
这是因为DataInputStream
继承了FilterInputStream
,而FilterInputStream
实现了close()
方法:
public void close() throws IOException {
in.close();
}
DataOutputStream
继承了其 close()
方法自 FilterOutputStream
,后者的文档指出:
关闭此输出流并释放与该流相关联的任何系统资源。
FilterOutputStream
的 close 方法调用其 flush 方法,然后调用其底层输出流的 close 方法。
所有 Writer
实现都应该是如此(尽管文档中没有说明)。
为避免在使用 Java 中的 Streams 时遇到内存问题,请使用以下模式:
// 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,这使得代码看起来不那么混乱,因为所有的Stream/Writer/Reader类都实现了它。请参见教程。