简体   繁体   中英

Will closing a DataInputStream also close the FileInputStream?

FileInputStream fstream = new FileInputStream(someFile.getPath());
DataInputStream in = new DataInputStream(fstream);

If i call in.close() , will it also close fstream ? My code is giving GC Exception as follows:

java.lang.OutOfMemoryError: GC overhead limit exceeded

Yes, DataInputStream.close() also closes your FileInputStream .

This is because DataInputStream inherits FilterInputStream which has the following implementation of the close() method:

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

Your DataOutputStream inherits its close() method from FilterOutputStream whose documentation states that:

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.

The same should be true for all Writer implementations (although it's not stated in the docs).


To avoid running into memory problems when working with Streams in Java, use this pattern:

// 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();
        }
    }
}

This looks less messy with Java7 because it introduces the AutoCloseable -interface , which is implemented by all Stream/Writer/Reader classes. See the tutorial .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM