1

Having a java.awt.image.BufferedImage I'm getting and returning a ByteArrayOutputStream by:

ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write( combined, "png", baos );
return baos;

Then I generate a base64 representation to be returned on a REST endpoint:

return new String(Base64.encodeBase64(baos.toByteArray()), Charset.forName("UTF-8"));

My question is: should I flush and close the baos?

(I've never understood properly when I should close a baos and when not, so any tip will be appreciated)

Ignasi
  • 5,887
  • 7
  • 45
  • 81

2 Answers2

2

My question is: should I flush and close the baos?

The good practice would be to always close an OutputStream but in case of a ByteArrayOutputStream, the methods flush and close don't do anything so it is not required (check the links to see by yourself).

From the Javadoc of close()

Closing a ByteArrayOutputStream has no effect.

From the Javadoc of OutputStream#flush() (since ByteArrayOutputStream doesn't override it)

The flush method of OutputStream does nothing.

Nicolas Filotto
  • 43,537
  • 11
  • 94
  • 122
1

It works like this:

the flush() method will some sort of push all remaining elements to their destination, like when you flush the toilet.

before using close() you should use flush() in order to make sure there isn't anything remaining, because if you close without everything sent it will probably get lost.

You should use flush() and close() after you have 'used the stream'.

This works for all OutputStreams.

Adrian K.
  • 118
  • 1
  • 8