Will closing a DataInputStream also close the File

2020-08-26 03:03发布

问题:

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

回答1:

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


回答2:

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.