2

I am using ObjectOutputStream to write the data into a file. Following is the code snippet.

try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(f))) 
{
    oos.writeObject(allObjects);
}

Questions:

  1. Do I need to split the object construction of OOS and FOS separately in try-with-resources? I assume that OOS internally also closes the FOS. So the above code line should be fine.
  2. Do I need to explicitly call flush?

The problem being I saw once the file was corrupted and while debugging I had the above mentioned queries.

nickb
  • 59,313
  • 13
  • 108
  • 143
Vikron
  • 25
  • 1
  • 6

2 Answers2

6
  1. No: Closing ObjectOutputStream will automatically close FileOutputStream

  2. No: The stream will be flushed automatically on close.

Maciej
  • 1,954
  • 10
  • 14
2

I believe developers should rely on the published general contract.

There is no evidence that an ObjectOutputStream's close() method calls flush().

OpenJDK's ObjectOutputStream#close is just a vendor implementation, I believe.

And it won't hurt if we flush on the try-with-resources.

try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(f))) {
    oos.writeObject(allObjects);
    oos.flush(); // What's possibly going wrong with this?
}
Jin Kwon
  • 20,295
  • 14
  • 115
  • 184