34

I need to convert a byte array to ByteArrayOutputStream so that I can display it on screen.

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
Arun
  • 3,701
  • 5
  • 32
  • 43
  • 5
    A `ByteArrayOutputStream` is meant to *receive* data. Are you sure you don't mean a `ByteArrayInputStream`? – Jon Skeet Sep 02 '13 at 14:30
  • With JDK/11, you can now use the utility provided to [write the complete byte array](https://stackoverflow.com/a/51789541/1746118) directly. – Naman Aug 10 '18 at 15:17

3 Answers3

61
byte[] bytes = ....;
ByteArrayOutputStream baos = new ByteArrayOutputStream(bytes.length);
baos.write(bytes, 0, bytes.length);

Method description:

Writes len bytes from the specified byte array starting at offset off to this byte array output stream.

Josh M
  • 11,611
  • 7
  • 39
  • 49
0

You can't display a ByteArrayOutputStream. What I suspect you are trying to do is

byte[] bytes = ...
String text = new String(bytes, "UTF-8"); // or some other encoding.
// display text.

You can make ByteArrayOutputStream do something similar but this is not obvious, efficient or best practice (as you cannot control the encoding used)

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
0

With JDK/11, you can make use of the writeBytes(byte b[]) API which eventually calls the write(b, 0, b.length) as suggested in the answer by Josh.

/**
 * Writes the complete contents of the specified byte array
 * to this {@code ByteArrayOutputStream}.
 *
 * @apiNote
 * This method is equivalent to {@link #write(byte[],int,int)
 * write(b, 0, b.length)}.
 *
 * @param   b     the data.
 * @throws  NullPointerException if {@code b} is {@code null}.
 * @since   11
 */
public void writeBytes(byte b[]) {
    write(b, 0, b.length);
}

The sample code would simply transform into --

byte[] bytes = new byte[100];
ByteArrayOutputStream baos = new ByteArrayOutputStream(bytes.length);
baos.writeBytes(bytes);
Naman
  • 27,789
  • 26
  • 218
  • 353