Java - ByteArrayOutputStream toByteArray() method



Description

The Java ByteArrayOutputStream toByteArray() method is used to return the current contents of the output stream as a byte array. This method creates a new byte array containing the same data as the internal buffer of the stream. It is useful for retrieving the data written to the stream in a format that can be processed further.

Declaration

Following is the declaration for java.io.ByteArrayOutputStream.toByteArray() method −

public byte[] toByteArray()

Parameters

NA

Return Value

The method returns byte array from this output stream.

Exception

NA

Example - Using ByteArrayOutputStream toByteArray() method

The following example shows the usage of Java ByteArrayOutputStream toByteArray() method. We've created a ByteArrayOutputStream reference and then initialized it with ByteArrayOutputStream object. Now we've written a bytearray to output stream using write() method and print each byte by iterating the byte array retrieved using toByteArray() method. Lastly in finally block, we close the stream using close() method.

ByteArrayOutputStreamDemo.java

package com.tutorialspoint;

import java.io.ByteArrayOutputStream;
import java.io.IOException;

public class ByteArrayOutputStreamDemo {
   public static void main(String[] args) throws IOException {
      byte[] bs = {65, 66, 67, 68, 69};
      ByteArrayOutputStream baos = null;      
      try {
         
         // create new ByteArrayOutputStream
         baos = new ByteArrayOutputStream();
      
         // write byte array to the output stream
         baos.write(bs);
            
         // for each byte in the buffer
         for (byte b : baos.toByteArray()) {            
            // print every byte
            System.out.println(b);
         }
         
      } catch(Exception e) {
         // if I/O error occurs
         e.printStackTrace();
      } finally {
         if(baos!=null)
            baos.close();
      }   
   }
}

Output

Let us compile and run the above program, this will produce the following result −

65
66
67
68
69

Example - Using ByteArrayOutputStream toByteArray() method

The following example shows the usage of Java ByteArrayOutputStream toByteArray() method. We've created a ByteArrayOutputStream reference and then initialized it with ByteArrayOutputStream object. Now we're writing multiple value to output stream and print each byte by iterating the byte array retrieved using toByteArray() method. Lastly in finally block, we close the stream using close() method.

ByteArrayOutputStreamDemo.java

package com.tutorialspoint;

import java.io.ByteArrayOutputStream;
import java.io.IOException;

public class ByteArrayOutputStreamDemo {
   public static void main(String[] args) throws IOException {
      ByteArrayOutputStream baos = null;      
      try {
        
         // create new ByteArrayOutputStream
         baos = new ByteArrayOutputStream();
         
         // writing bytes to output stream
         baos.write(75);
         baos.write(65);
         
         // for each byte in the buffer
         for (byte b : baos.toByteArray()) {            
            // print every byte
            System.out.println(b);
         }
      } catch(Exception e) {
         // if I/O error occurs
         e.printStackTrace();
      } finally {
         if(baos!=null)
            baos.close();
      }   
   }
}

Output

Let us compile and run the above program, this will produce the following result −

75
65

Example - Using toByteArray() to Retrieve Data from the Stream

The following example shows the usage of Java ByteArrayOutputStream toByteArray() method.

ByteArrayOutputStreamDemo.java

package com.tutorialspoint;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Arrays;

public class ByteArrayOutputStreamDemo {
   public static void main(String[] args) {
      // Create a ByteArrayOutputStream
      ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

      try {
         // Write some data to the stream
         outputStream.write("Hello, World!".getBytes());

         // Convert the stream content to a byte array
         byte[] byteArray = outputStream.toByteArray();

         // Print the byte array
         System.out.println("Byte array: " + Arrays.toString(byteArray));

         // Convert the byte array back to a string and print it
         String content = new String(byteArray);
         System.out.println("String content: " + content);

         // Close the stream (optional for ByteArrayOutputStream)
         outputStream.close();
      } catch (IOException e) {
         System.err.println("IOException occurred: " + e.getMessage());
      }
   }
}

Output

Let us compile and run the above program, this will produce the following result −

Byte array: [72, 101, 108, 108, 111, 44, 32, 87, 111, 114, 108, 100, 33]
String content: Hello, World!

Explanation

  • The string "Hello, World!" is written to the ByteArrayOutputStream.

  • The toByteArray() method is called to retrieve the content of the stream as a new byte array.

  • The byte array is printed using Arrays.toString() for better visualization of the raw byte data.

  • The byte array is converted back to a string using the String constructor to demonstrate how the data can be reused.

  • Although calling close() on a ByteArrayOutputStream has no real effect, it is included for consistency.

Key Points

  • Purpose of toByteArray()

    • Converts the current contents of the ByteArrayOutputStream to a new byte array.

  • New Array

    • The returned byte array is independent of the stream, meaning modifications to the byte array do not affect the original stream.

  • Use Case

    • Useful when you need to pass the data to other APIs or write it to other output destinations.

  • Internal Efficiency

    • The method avoids exposing the internal buffer directly, ensuring encapsulation and data integrity.

java_bytearrayoutputstream.htm
Advertisements