ilopezluna ilopezluna - 1 year ago 145
Java Question

Java BufferedImage to ByteArrayOutputStream without close ByteArrayOutputStream

Having a

I'm getting and returning a

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 Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download