dsa

Java ByteArrayOutputStream Class

In this tutorial, we will learn about Java ByteArrayOutputStream and its methods with the help of examples.

Java ByteArrayOutputStream class is used to write common data into multiple files. In this stream, the data is written into a byte array which can be written to multiple streams later.
The ByteArrayOutputStream holds a copy of data and forwards it to multiple streams.
The buffer of ByteArrayOutputStream automatically grows according to data.

The ByteArrayOutputStream is a subclass of the Java OutputStream.

Java ByteArrayOutputStream class declaration

public class ByteArrayOutputStream extends OutputStream 

Fields

Java ByteArrayOutputStream class methods

Sr.No. Method & Description
1

public void reset()

This method resets the number of valid bytes of the byte array output stream to zero, so all the accumulated output in the stream will be discarded.

2

public byte[] toByteArray()

This method creates a newly allocated Byte array. Its size would be the current size of the output stream and the contents of the buffer will be copied into it. Returns the current contents of the output stream as a byte array.

3

public String toString()

Converts the buffer content into a string. Translation will be done according to the default character encoding. Returns the String translated from the buffer's content.

4

public void write(int w)

Writes the specified array to the output stream.

5

public void write(byte []b, int of, int len)

Writes len number of bytes starting from offset off to the stream.

6

public void writeTo(OutputStream outSt)

Writes the entire content of this Stream to the specified stream argument.