Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

ByteArrayOutputStream — writing bytes in memory

ByteArrayOutputStream collects bytes in memory. Learn writing, independent data snapshots, and why close() has no effect.

Version: Java SE 21; repository runtime, production runtime not attested

Syntax

ByteArrayOutputStream out = new ByteArrayOutputStream();
out.write(intValue);
out.write(bytes, offset, length);
byte[] snapshot = out.toByteArray();
out.close();

ByteArrayOutputStream in java.io is an output stream storing bytes in an automatically growing array, not a file.

ByteArrayOutputStream.write(int) appends one byte; write(byte[], int, int) appends an array segment specified by starting index and byte count. An invalid range causes IndexOutOfBoundsException.

ByteArrayOutputStream.toByteArray() returns a new array copying the accumulated bytes. Modifying the copy does not modify the stream. Copying requires extra memory; avoid accumulating unbounded data.

ByteArrayOutputStream.close() has no effect: further writes are allowed and data remains accessible. Its signature still declares IOException, which the example accommodates.

Examples

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

public class Main {
    public static void main(String[] args) throws IOException {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        out.write(65);
        out.write(new byte[] {66, 67}, 0, 2);
        byte[] snapshot = out.toByteArray();
        snapshot[0] = 90;
        out.close();
        out.write(68);
        System.out.println(Arrays.toString(snapshot));
        System.out.println(Arrays.toString(out.toByteArray()));
    }
}

Result

[90, 66, 67]
[65, 66, 67, 68]

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources