ByteArrayOutputStream

ByteArrayOutputStream is a memory-based stream that collects output data in an internal byte array. It’s useful when you want to build a byte array dynamically (e.g., generating PDF content, processing images, etc.).It automatically resizes its internal buffer as data is written.

Commonly Used Constructors and Methods

Simple Program – Writing and Printing Byte Array

LotusJavaPrince wants to store the message "Mahesh is brilliant!" in memory using ByteArrayOutputStream and print it as a string.

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

public class SimpleByteArrayOutputStream {
    public static void main(String[] args) {
        String message = "Mahesh is brilliant!";

        try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
            baos.write(message.getBytes());

            // Convert to byte array and print as string
            String result = baos.toString();
            System.out.println("Output Stream Result: " + result);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Output:

Output Stream Result: Mahesh is brilliant!

Problem Statement:

Mahesh is building a message collector system where various components write logs (e.g., System, Auth, Error) to a common in-memory stream. Once collected, LotusJavaPrince will convert them into one report string using ByteArrayOutputStream.

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

public class LogCollector {
    public static void main(String[] args) {
        try (ByteArrayOutputStream logStream = new ByteArrayOutputStream()) {
            
            // Component 1: System log
            String systemLog = "System Started Successfully.\n";
            logStream.write(systemLog.getBytes());

            // Component 2: Authentication log
            String authLog = "User Mahesh logged in.\n";
            logStream.write(authLog.getBytes());

            // Component 3: Error log
            String errorLog = "Warning: Low Disk Space.\n";
            logStream.write(errorLog.getBytes());

            // Final report generation
            String finalReport = logStream.toString();
            System.out.println("------ System Log Report ------");
            System.out.println(finalReport);

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Output:

------ System Log Report ------
System Started Successfully.
User Mahesh logged in.
Warning: Low Disk Space.

The ByteArrayOutputStream class is a memory-based output stream that plays a vital role in modern Java applications where dynamic and flexible byte data storage is needed. Unlike file or network-based output streams, ByteArrayOutputStream stores data in memory, making it fast, reusable, and ideal for temporary or intermediate output handling.

Scroll to Top