Tech and Media Labs
This site uses cookies to improve the user experience.




Java IO: ByteArrayOutputStream

Jakob Jenkov
Last update: 2014-11-16

The ByteArrayOutputStream class of the Java IO API allows you to capture data written to a stream in an array. You write your data to the ByteArrayOutputStream and when you are done you call the ByteArrayOutputStream's method toByteArray() to obtain all the written data in a byte array.

ByteArrayOutputStream Example

Here is a simple ByteArrayOutputStream example:

ByteArrayOutputStream output = new ByteArrayOutputStream();

//write data to output stream

byte[] bytes = output.toByteArray();

A ByteArrayOutputStream can be handy in situations where you have a component that outputs its data to an OutputStream, but where you need it as a byte array.

Note: The proper exception handling has been skipped here for the sake of clarity. To learn more about correct exception handling, go to Java IO Exception Handling.

A Note on close()

Being a subclass of OutputStream the ByteArrayOutputStream also has a close() method. But calling the close() method has no effect on the ByteArrayOutputStream.

Jakob Jenkov




Copyright  Jenkov Aps
Close TOC