0

Does it cause any issues or draw backs (performance hit, memory leak, etc.) to initialize an ObjectOutputStream with

ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(highScorePath));

vs.

FileOutputStream fos = new FileOutputStream(highScorePath);
ObjectOutputStream oos = new ObjectOutputStream(fos);

Part of me wants to go with the top one because you do not have to have two separate variables for something that is only going to serve one purpose. But at the same time, I want to go with the bottom one, since in order to free up resources, you must explicitly call .close() on both fos and oos. What I am not sure about is if I went with the top option and called oos.close(), would that also properly close the FileOutputStream, or would that cause a memory leak?

  • 2
    Both of your examples perform exactly the same. Closing the ObjectOutputStream will close the underlying FileOutputStream (since you are using the default implementation), and the ObjectOutputStream will keep a handle on the FileOutputStream no matter what, so it doesn't matter if you create another variable for it or not. – Charlie Armstrong Oct 14 '20 at 18:37
  • 1
    “…you must explicitly call `.close()` on both `fos` and `oos`.” You are mistaken. All Java SE OutputStream implementations which wrap another OutputStream have `close()` methods which will close their underlying streams. The same goes for wrapping InputStreams, Readers, and Writers. – VGR Oct 14 '20 at 19:21
  • For those that asked (and those who's questions got deleted by SO when I verified this as a duplicate question), yes those questions answered it. I didn't know how to word my problem when I was DuckDucking help. – DuluthIsSuperior Oct 14 '20 at 22:19

0 Answers0