关闭DataInputStream还会关闭FileInputStream吗?

Ady*_*dyz 7 java inputstream

FileInputStream fstream = new FileInputStream(someFile.getPath());
DataInputStream in = new DataInputStream(fstream);
Run Code Online (Sandbox Code Playgroud)

如果我打电话in.close(),它还会关闭fstream吗?我的代码给出了GC Exception,如下所示:

java.lang.OutOfMemoryError:超出了GC开销限制

And*_*niy 7

是的,DataInputStream.close()也关闭你的FileInputStream.


Luk*_*uth 5

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();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

这看起来不太凌乱与Java7,因为它引入了AutoCloseable-接口,这是所有的流/写入/读取器类实现的.请参阅教程.