将关闭DataInputStream还将关闭FileInputStream吗?

问题描述 投票:9回答:2
FileInputStream fstream = new FileInputStream(someFile.getPath());
DataInputStream in = new DataInputStream(fstream);

如果我呼叫in.close(),也会关闭fstream吗?我的代码给出了GC异常,如下所示:

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

java inputstream
2个回答
8
投票

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

这是因为DataInputStream继承了FilterInputStream,它具有close()方法的以下实现:

    public void close() throws IOException {
        in.close();
    }

6
投票

您的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

© www.soinside.com 2019 - 2024. All rights reserved.