How can you force a flush on an OutputStream object without closing it?

GrowinMan picture GrowinMan · Apr 16, 2012 · Viewed 20.1k times · Source

My question lies on the following assumptions which I hope are true, because I believe these as I read them while Googling my problems:

  1. Closing a Socket's OutputStream closes the socket too
  2. The flush() method of OutputStream does nothing

So I basically need to anyhow flush the data out of my OutputStream object for my app to work.

If you're interested in details then please see the following two links :

. Weird behavior : sending image from Android phone to Java server (code working)

This issue was resolved by closing the OutputStream. Doing that flushed all the data to the other end of the socket and made my app working further but this fix soon gave rise to problem number 2 - the corresponding socket also gets closed :

. SocketException - 'Socket is closed' even when isConnected() returns true

Answer

smichak picture smichak · Apr 16, 2012

You can call the flush method of OutputStream instead of close. The concrete classes inheriting from OutputStream will override flush() to do something other than nothing (writing the data to a file or sending it over the network).