Search code examples
javaandroidbytearrayoutputstream

Closing ByteArrayOutputStream in an Android application


In an Android application I'm sending a picture taken from the Camera Intent so I need to transform a Bitmap to a byte array. To do this I use a ByteArrayOutputStream as follow:

private byte[] getRawImageData(Bitmap source) {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    byte[] rawImageData = null;
    try {
        source.compress(CompressFormat.JPEG, DEFAULT_COMRESSION, baos);
        rawImageData = baos.toByteArray();
    } finally {
        try {
            baos.close();
        } catch (IOException e) {
            // handle exception here
        }
    }
    return rawImageData;
}

Everything works fine and all, the real question is the difference in the documentation of ByteArrayOutputStream between the javadoc and the doc from Android.

The Javadoc reads

Closing a ByteArrayOutputStream has no effect.

the Android doc reads:

Closes this stream. This releases system resources used for this stream.

I am closing the stream not matter what but I would like to know which documentation is correct and why they are different.


Solution

  • ByteArrayOutputStream is a memory based stream (managed and populated by user in code), so there is no effect when you call close() on it. The only way to clean up its memory foot-print is by revoking all the references to this object. By then, the Garbage Collector will kick-in any time soon in future and do its job to clean up such objects.

    However, closing a stream is required when you engage resources like files or input/output socket streams (e.g. OutputStream, InputStream). When you call close() on such streams, the JVM safely releases their local-storage/occupied-memory and avoids any OutOfMemory issues.

    So in general, it is good (and sometimes vital) to call close() on any type of stream when it is no longer required, but more importantly, it is better to know why should we call.