00:00

ByteArrayOutputStream Class in Java: Writing Bytes to Memory

Last updated:

Sometimes you need the bytes an API writes, but not in a file: to send them over the network, store them in a database or check them in a test. ByteArrayOutputStream is an output stream that collects everything written to it in a byte array that grows automatically.

This tutorial covers its constructors, methods and two practical examples.

1. What Is ByteArrayOutputStream in Java?

ByteArrayOutputStream is a subclass of OutputStream whose destination is an internal byte[] in memory. When the array is full, the class allocates a larger one and copies the data, so you never need to know the final size in advance. It has been part of Java since version 1.0.

2. ByteArrayOutputStream Class Hierarchy

ByteArrayOutputStream class hierarchyByteArrayOutputStream extends the abstract class OutputStream, which extends Object, and implements Closeable, Flushable and AutoCloseable. It writes into a growing byte array; the result is obtained with toByteArray, toString with a Charset, or writeTo another OutputStream.ObjectextendsOutputStreamabstract classextendsByteArrayOutputStreamwrites into a growing byte[]CloseableFlushableAutoCloseableimplementsGet the result withtoByteArray()toString(Charset)writeTo(OutputStream)

Swipe sideways to see the whole diagram.

3. Constructors of ByteArrayOutputStream

ConstructorDescription
ByteArrayOutputStream()Starts with a small buffer that grows as needed.
ByteArrayOutputStream(int size)Starts with size bytes of capacity; useful when you know roughly how much will be written.

4. Commonly Used Methods

MethodDescription
void write(int b) / write(byte[] b, int off, int len)Appends bytes to the buffer.
void writeBytes(byte[] b)Appends the whole array, without IOException (Java 11).
byte[] toByteArray()Returns a copy of the bytes written so far.
String toString(Charset charset)Decodes the bytes into text (Java 10).
int size()Number of bytes written.
void writeTo(OutputStream out)Writes the whole content to another stream.
void reset()Empties the stream so its buffer can be reused.
void close()Has no effect; the stream can still be used.

5. Example: Building a Report in Memory

A finance dashboard builds a CSV report row by row in memory and saves it to disk with a single write.

ReportBuilder.java
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;

public class ReportBuilder {
    public static void main(String[] args) throws IOException {
        ByteArrayOutputStream report = new ByteArrayOutputStream();   // grows automatically

        report.writeBytes("Branch,Revenue\n".getBytes(StandardCharsets.UTF_8));   // Java 11
        String[][] rows = {{"Pune", "420000"}, {"Indore", "315500"}, {"Kochi", "298750"}};
        for (String[] row : rows) {
            report.writeBytes((row[0] + "," + row[1] + "\n").getBytes(StandardCharsets.UTF_8));
        }
        System.out.println("Report built in memory: " + report.size() + " bytes");

        // Only now touch the disk, in one write
        Path file = Files.createTempFile("revenue", ".csv");
        try (OutputStream out = Files.newOutputStream(file)) {
            report.writeTo(out);
        }
        System.out.println("Bytes on disk:          " + Files.size(file));
        System.out.print(report.toString(StandardCharsets.UTF_8));   // Java 10
        Files.delete(file);
    }
}
Output
Report built in memory: 54 bytes
Bytes on disk:          54
Branch,Revenue
Pune,420000
Indore,315500
Kochi,298750

How the code works

  1. writeBytes() (Java 11) appends each line's UTF-8 bytes; the internal array grows automatically.
  2. size() reports the 54 bytes collected so far.
  3. writeTo() copies the content to a file stream in one call.
  4. toString(StandardCharsets.UTF_8) (Java 10) turns the bytes back into text for display.

6. Example: Capturing Console Output

A legacy method prints a greeting directly to the console. To test it, the program temporarily redirects System.out into a ByteArrayOutputStream.

CaptureOutput.java
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.nio.charset.StandardCharsets;

public class CaptureOutput {

    // Legacy code that can only print to the console
    static void printGreeting(String name) {
        System.out.println("Welcome back, " + name + "!");
    }

    public static void main(String[] args) {
        PrintStream original = System.out;
        ByteArrayOutputStream captured = new ByteArrayOutputStream();

        System.setOut(new PrintStream(captured, true, StandardCharsets.UTF_8));
        try {
            printGreeting("Priya");                 // goes into the byte array, not the console
        } finally {
            System.setOut(original);                // always restore the real console
        }

        String text = captured.toString(StandardCharsets.UTF_8).strip();
        System.out.println("Captured: \"" + text + "\"");
        System.out.println("Correct greeting: " + text.equals("Welcome back, Priya!"));
    }
}
Output
Captured: "Welcome back, Priya!"
Correct greeting: true

How the code works

  1. System.setOut() replaces the console with a PrintStream that writes into the byte array.
  2. Everything printGreeting() prints is captured instead of shown.
  3. The finally block always restores the original console, even if the method throws.
  4. strip() removes the line separator, so the comparison works on every operating system.

7. Important Features

  • The buffer grows automatically; there is no fixed maximum other than available memory and array size limits.
  • toByteArray() returns a copy, so later writes do not change arrays you already received.
  • Its own write methods do not throw IOException.
  • close() has no effect.

8. Common Mistakes and Best Practices

  • Calling toString() without a charset. It uses the default charset; pass StandardCharsets.UTF_8.
  • Calling toByteArray() repeatedly in a loop. Each call copies the whole buffer; call it once at the end.
  • Collecting huge outputs in memory. Write large data directly to a file instead.
  • Forgetting to restore System.out. Always do it in a finally block.

9. Java Version Improvements and Java 25 Updates

Java versionChange
Java 1.0 and 1.1ByteArrayOutputStream; toString(String charsetName) in 1.1.
Java 10toString(Charset).
Java 11writeBytes(byte[]).
Java 25No changes; the class is fully supported.

10. Summary

  • ByteArrayOutputStream collects written bytes in a growing in-memory array.
  • Get the result with toByteArray(), toString(Charset) or writeTo().
  • It is ideal for building data before sending it and for capturing output in tests.
  • Always decode with an explicit charset, and avoid it for very large data.

Related Tutorials

11. Official Java Documentation References