Table of Contents
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
package org.arpit.java2blog; import java.io.ByteArrayOutputStream; import java.io.IOException; public class OutputStreamToByteArray { public static void main(String[] args) throws IOException { String str="Java2blog"; // Creates OutputStream ByteArrayOutputStream baos = new ByteArrayOutputStream(); // Get bytes from String byte[] array = str.getBytes(); // Write data to OutputStream baos.write(array); // Convert OutputStream to byte array byte bytes[] = baos.toByteArray(); System.out.println("Print output:"); for(int x = 0; x < bytes.length; x++) { // Print original characters System.out.print((char)bytes[x] + ""); } System.out.println(" "); } } |
Output:
Print output:
Java2blog
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
package org.arpit.java2blog; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.nio.ByteBuffer; public class OutputStreamToByteBuffer { public static void main(String[] args) throws IOException { String str="Java2blog"; // Creates OutputStream ByteArrayOutputStream baos = new ByteArrayOutputStream(); // Get bytes from String byte[] array = str.getBytes(); // Write data to OutputStream baos.write(array); // Get bytes[] from ByteArrayOutputStream byte bytes[] = baos.toByteArray(); // Convert bytep[] to ByteBuffer ByteBuffer bb= ByteBuffer.wrap(bytes); System.out.println(bb); } } |
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?
Let us know if this post was helpful. Feedbacks are monitored on daily basis. Please do provide feedback as that\'s the only way to improve.