javaflushfileoutputstreamobjectoutputstream

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.


Solution

    1. No: Closing ObjectOutputStream will automatically close FileOutputStream

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