1. Convert OutputStream to byte array using toByteArray() method
2. Convert OutputStream to ByteBuffer using the wrap() method
Read Also: Convert byte array to Base64 String in Java with examples
1. Convert OutputStream to byte array using toByteArray() method
We can easily convert OutputStream to a byte array by following the below steps:1. Create an object of ByteArrayOutputStream.
2. Write data to ByteArrayOutputStream.
3. Extract byte[] from ByteArrayOutputStream using toByteArray() method as shown below in the example.
Java Program
import java.io.IOException;
import java.io.ByteArrayOutputStream;
public class OutputStreamToByteArray1 {
public static void main(String args[]) throws IOException {
// Given string
String string1 = "Alive is Awesome";
// Creating ByteArrayOutputStream object
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
// Fetch Bytes from String
byte[] array = string1.getBytes();
// Writing data to an output stream
outputStream.write(array);
// Converting output stream to byte array
byte[] bytes = outputStream.toByteArray();
// Printing the byte array
System.out.println("Output: ");
for(int i=0; i < bytes.length; i++)
{
// Show original characters
System.out.print((char)bytes[i] + "");
}
}
}
Output:
Alive is Awesome
2. Convert OutputStream to ByteBuffer using the wrap() method
We can easily convert OutputStream to ByteBuffer by following the below steps:1. First, the ByteArrayOutputStream class instance should be created.
2. Write the data to the ByteArrayOutputStream.
3. Extract byte[] from ByteArrayOutputStream using toByteArray() function.
4. Converting byte array to ByteBuffer using ByteBuffer.wrap(byte[]) function as shown below in the example.
Java Program
import java.io.IOException;
import java.nio.ByteBuffer;
import java.io.ByteArrayOutputStream;
public class OutputStreamToByteBuffer1 {
public static void main(String args[]) throws IOException {
// Input string
String string1 = "Be in present";
// Creating ByteArrayOutputStream instance
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
// Fetching Bytes from given input string
byte[] array = string1.getBytes();
// write data to output stream
outputStream.write(array);
// Converting output stream to byte array
byte[] bytes = outputStream.toByteArray();
// Converting byte array to ByteBuffer
ByteBuffer bufferObject = ByteBuffer.wrap(bytes);
// Printing the ByteBuffer
System.out.println(bufferObject);
}
}
Output:
java.nio.HeapByteBuffer[pos=0 lim=13 cap=13]
That's all for today. Please mention in the comments if you have any questions related to how to convert OutputStream to byte array in Java with examples.