Java ByteArrayOutputStream Class with Examples

Java is the most widely and useful language.

An array of output data (in bytes) can be written using the Java.io package’s ByteArrayOutputStream class.
The abstract class OutputStream is extended by it.

Explanation

  • Common data can be written into several files using the Java ByteArrayOutputStream class.
  • The information is written to a byte array in this stream, which can then be written to other streams.
  • Data is copied and sent to several streams via the ByteArrayOutputStream.

Declaration

public class ByteArrayOutputStream extends OutputStream

How to create:

  • The java.io.ByteArrayOutputStream package must be imported before we can create a byte array output stream. Here’s how to generate an output stream after importing the package.
  • ByteArrayOutputStream out = new ByteArrayOutputStream();
  • An output stream has been created that will write data to a byte array with a default size of 32 bytes. However, we can change the array’s initial size.
  • ByteArrayOutputStream out = new ByteArrayOutputStream(int size);

Constructors:

Constructor Description
ByteArrayOutputStream() Generates a new output stream for the byte array, initially with a capacity of 32 bytes, but it can be expanded if needed.
ByteArrayOutputStream(int size) Generates a new output stream for a byte array with a buffer capacity of the given size, expressed in bytes.

Methods Table:

Methods Description
int size() It is employed to provide the buffer’s current size.
byte[] toByteArray() It’s employed to generate a freshly assigned byte array.
String toString() It is employed to transform the content into a string by decoding the character set by default on the platform.
String toString(String charsetName) It is employed to transform the data into a string by decoding bytes with a given charsetName.
void write(int b) It is employed to write the given byte to the output stream of the byte array.
void write(byte[] b, int off, int len It is used to write len bytes to the byte array output stream from a given byte array, beginning at the offset.
void writeTo(OutputStream out) It is used to write all of a byte array output stream’s content to the designated output stream.
void reset() It is employed to set a byte array output stream’s count field to zero.
void close() It’s employed to terminate the ByteArrayOutputStream.

Fields Tables:

Modifier Description
protected byte[] Buf

The data is stored in the buffer 

protected int Count

The buffer consists of number of valid bytes.

Example

package com.java;  
import java.io.*;  
public class TechVidvan{  
public static void main(String args[])throws Exception{    
      FileOutputStream fout1=new FileOutputStream("f1.txt");    
      FileOutputStream fout2=new FileOutputStream("f2.txt");    
        
      ByteArrayOutputStream bout=new ByteArrayOutputStream();    
      bout.write(65);    
      bout.writeTo(fout1);    
      bout.writeTo(fout2);    
        
      bout.flush();    
      bout.close();//has no effect    
      System.out.println("TechVidvan Tutorials");    
     }    
    }

Output:
TechVidvan Tutorials

f1.txt:
A
f2.txt:
A

Example:

import java.io.*;

public class TechVidvan {

    public static void main(String args[]) {
        ByteArrayOutputStream aOutput = new ByteArrayOutputStream(10);

        int targetSize = 10;

        while (aOutput.size() < targetSize) {
            aOutput.write("TechVidvan".getBytes(), 0, 10);
        }

        byte a[] = aOutput.toByteArray();
        System.out.println("Printing the content");

        for (int x = 0; x < a.length; x++) {
            System.out.print((char) a[x] + "   ");
        }
        System.out.println("  ");

        int c;
        ByteArrayInputStream aInput = new ByteArrayInputStream(a);
        System.out.println("Converting into Upper case ");

        for (int y = 0; y < 1; y++) {
            while ((c = aInput.read()) != -1) {
                System.out.println(Character.toUpperCase((char) c));
            }
            aInput.reset();
        }
    }
}

Output:
Printing the content
T e c h V i d v a n
Converting into Upper case
T
E
C
H
V
I
D
V
A
N

Fields:

  • protected byte[] buf: The buffer used to hold data.
  • protected int count: the buffer’s total number of valid bytes.

Access Data from Java ByteArrayOutputStream

  • toString() – returns all of the output stream’s data in string form;
  • toByteArray() – returns the array that is present inside the output stream.

Methods of Java ByteArrayOutputStream:

  • size() – provides the array’s size in the output stream.
  • flush() – makes the output stream empty

Difference between ByteArrayOutputStream and FioeOutputStream:

  • Since the ByteArrayOutputStream saves the entire content in Java’s memory (in the form of a byte[]), it consumes more memory.
  • Because the FileOutputStream writes straight to disk, it uses less memory.

Uses:

  • The entire byte array’s contents are written to the OutputStream using the write(byte[] bytes) method.
  • The byte array’s length bytes are sent to the OutputStream by the write(byte[] bytes, int offset, int length) method, which begins at index offset.
  • 32-byte data makes a fresh output stream for a byte array. The buffer’s initial capacity is 32 bytes, however it can be expanded if needed.

Benefits of Java ByteArrayOutputStream:

  • It is employed to transform the content into a string by decoding the character set by default on the platform.
  • It is employed to transform the material into a string by utilizing a given charsetName to decode the bytes.
  • To save the data, ByteArrayOutputStream keeps an internal array of bytes.
  • An array of bytes is created from a string using the program’s getBytes() method.

Conclusion

The ByteArrayOutputStream used in various output data stream in Java. We have undergone many purposes and examples of it.