ilopezluna ilopezluna - 22 days ago 6
Java Question

Java BufferedImage to ByteArrayOutputStream without close ByteArrayOutputStream

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)

Answer

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.

Comments