Vikron
Vikron

Reputation: 25

ObjectOutputStream in try-with-resources

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.

Upvotes: 2

Views: 1964

Answers (2)

Jin Kwon
Jin Kwon

Reputation: 22017

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?
}

Upvotes: 2

Maciej
Maciej

Reputation: 1994

  1. No: Closing ObjectOutputStream will automatically close FileOutputStream

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

Upvotes: 6

Related Questions