YouTip LogoYouTip

Java Bytearrayoutputstream

Java ByteArrayOutputStream Class

Java ByteArrayOutputStream Class

Java Tutorial

Java Object-Oriented

Java Advanced Tutorial

Java Constructors

Java Scanner Class

Java ByteArrayOutputStream Class

Java Stream (Stream) Java Stream (Stream)


The byte array output stream creates a byte array buffer in memory, and all data sent to the output stream is stored in this byte array buffer. There are several ways to create a byte array output stream object.

The following constructor creates a buffer of 32 bytes (default size).

OutputStream bOut = new ByteArrayOutputStream();

Another constructor creates a buffer of size a bytes.

OutputStream bOut = new ByteArrayOutputStream(int a)

After successfully creating a byte array output stream object, you can refer to the methods in the following list to perform write operations or other operations on the stream.

No. Method Description
1 public void reset() Resets the count field of this byte array output stream to zero, thereby discarding all currently accumulated data output in the output stream.
2 public byte[] toByteArray() Creates a newly allocated byte array. The size of the array is the same as the current size of the output stream, and its content is a copy of the current output stream.
3 public String toString() Converts the content of the buffer into a string, converting bytes to characters according to the platform's default character encoding.
4 public void write(int w) Writes the specified byte to this byte array output stream.
5 public void write(byte []b, int off, int len) Writes len bytes from the specified byte array starting at offset off to this byte array output stream.
6 public void writeTo(OutputStream outSt) Writes the entire contents of this byte array output stream to the specified output stream parameter.

Example

The following example demonstrates the use of ByteArrayInputStream and ByteArrayOutputStream:

← Java DataoutputstreamJava Datainputstream β†’