Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

ByteArrayOutputStream: copying bytes and closing the stream

Get an independent copy of the bytes written in memory and learn why this stream remains usable after `close()`.

Version: Java SE 21

Syntax

import java.io.ByteArrayOutputStream;

// Java SE 21: instance method signatures
public byte[] toByteArray()
public void close() throws java.io.IOException

java.io.ByteArrayOutputStream stores bytes in an internal array in memory. The buffer grows automatically as needed, so its capacity can exceed the number of bytes written.

ByteArrayOutputStream.toByteArray() creates a new byte[] each time you call it, containing only the written bytes in order. Its length matches size() at the time of the call. Later writes do not change the copy, and editing the copy does not change the buffer. You do not need to close the stream first.

ByteArrayOutputStream.close() has no effect: it neither clears nor releases the buffer, and you can still write bytes and take copies afterward. The signature still declares the checked exception IOException, so callers must catch or declare it. Do not assume other output streams behave the same way.

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 buffer = new ByteArrayOutputStream();
        buffer.write(10);
        buffer.write(20);
        byte[] snapshot = buffer.toByteArray();

        buffer.close();
        buffer.write(30);
        System.out.println(Arrays.toString(snapshot));

        snapshot[0] = 99;
        System.out.println(Arrays.toString(buffer.toByteArray()));
    }
}

Result

[10, 20]
[10, 20, 30]

The first line shows that appending `30` after closing did not change the earlier copy. The second shows that setting `snapshot[0]` to `99` did not change the buffer, which accepted `30` despite being closed.

Related lessons

  • Java · Lesson 60 · Intermediate · Version: 2

Sources