Convert Outputstream to Byte Array in Java

Convert OutputStream to byte array in java

In this post, we will see how to convert OutputStream to Byte array in Java.

Convert OutputStream to Byte array in Java

Here are steps to convert OutputStream to Byte array in java.

  • Create instance of ByteArrayOutputStream baos
  • Write data to ByteArrayOutputStream baos
  • Extract byte[] using toByteArray() method.

Output:

Print output:
Java2blog

Convert OutputStream to ByteBuffer in Java

To convert OutputStream to ByteBuffer in Java, we need to add one more step to above method.

  • Create instance of ByteArrayOutputStream baos
  • Write data to ByteArrayOutputStream baos
  • Extract byte[] using toByteArray() method.
  • Convert byte array to ByteBuffer using ByteBuffer.wrap(byte[]) method.

Output:

java.nio.HeapByteBuffer[pos=0 lim=9 cap=9]

That’s all about how to convert Outputstream to Byte Array in Java.

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *