furry furry - 27 days ago 19
Java Question

Do I need to close a stream?

Do I need to close a FileOutputStream in the following example? And why?

FileOutputStream fos = new FileOutputStream("bytes.info");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(data);
oos.close();

fgb fgb
Answer

If there were no exceptions thrown, then the FileOutputStream would be closed by ooo.close().

An exception thrown in writeObject would prevent any of the streams from being closed. So the close call should be in a finally block.

There's the additional problem that the ObjectOutputStream could throw an exception in its constructor. It writes the stream header in the constructor which can cause an exception. In this case, the FileOutputStream needs to be closed, but calling oos.close() is not possible because there's no reference to the ObjectOutputStream. So you really need two separate calls to close, one for each stream, both in finally blocks.

Using try-with-resources takes care of all of this for you:

try(
    FileOutputStream fos = new FileOutputStream("bytes.info");
    ObjectOutputStream oos = new ObjectOutputStream(fos)
) {
    oos.writeObject(data);
}
Comments