Will closing a DataInputStream also close the FileInputStream?
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.