Java ByteArrayOutputStream

Jakob Jenkov
Last update: 2019-11-15

The Java ByteArrayOutputStream class, java.io.ByteArrayOutputStream of the Java IO API enables you to capture data written to a stream in a byte array. You write your data to the ByteArrayOutputStream and when you are done you call the its toByteArray() method to obtain all the written data in a byte array.

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

ByteArrayOutputStream Example

Here is a simple ByteArrayOutputStream example:

ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

//write data to byteArrayOutputStream

byte[] bytes = byteArrayOutputStream.toByteArray();

Create a ByteArrayOutputStream

To use a Java ByteArrayOutputStream you must first create an instance of it. Here is how you create an instance of a ByteArrayOutputStream :

ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

Write Bytes to ByteArrayOutputStream

Since the Java ByteArrayOutputStream class is a subclass of the Java OutputStream class, you write bytes to it using the same write methods that OutputStream has:

  • write(int byteToWrite)
  • write(byte[] bytesToWrite, int offset, int length)

The the Java OutputStream Tutorial for more information about how to write bytes to an OutputStream.

toByteArray()

Once you have finished writing to the ByteArrayOutputStream you can obtain all the bytes written as a Java byte array, using the ByteArrayOutputStream toByteArray() method. Here is an example:

byte[] bytes = byteArrayOutputStream.toByteArray();

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

Featured Videos

Java Generics

Java ForkJoinPool

P2P Networks Introduction



















Close TOC
All Tutorial Trails
All Trails
Table of contents (TOC) for this tutorial trail
Trail TOC
Table of contents (TOC) for this tutorial
Page TOC
Previous tutorial in this tutorial trail
Previous
Next tutorial in this tutorial trail
Next