ByteArray Streams Capture And Replay

Capture produced bytes in a ByteArrayOutputStream, replay them through a ByteArrayInputStream, and reuse the same buffer after reset without reallocating.

JavaData Integrity

Code

snippet
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

public class MemoryWire {

    public static void main(String[] args) throws IOException {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        out.write("header|".getBytes(StandardCharsets.UTF_8));
        out.write(new byte[] {1, 2, 3});

        byte[] payload = out.toByteArray(); // 快照:之后的写入不影响这份拷贝
        System.out.println("captured " + payload.length + " bytes");

        ByteArrayInputStream in = new ByteArrayInputStream(payload);
        System.out.println("replayed: " + new String(in.readAllBytes(), StandardCharsets.UTF_8));

        out.reset(); // 计数归零,内部缓冲区复用,不重新分配
        out.write('X');
        System.out.println("size after reset+write: " + out.size());
        System.out.println("snapshot unchanged    : " + payload.length);
    }
}

How the logic is organized

The code’s whole job belongs to the class MemoryWire.

Watch out for

  • Every symbol it touches is a built-in — nothing needs fetching.

Using it

Output tags name each step: captured, replayed:, size after reset+write:.

Key statements

ByteArrayInputStream in = new ByteArrayInputStream(payload);
ByteArrayOutputStream out = new ByteArrayOutputStream();
out.write("header|".getBytes(StandardCharsets.UTF_8));

Interactive Tools for This Topic

FAQ

What does ByteArray Streams Capture And Replay print when run?
Run it as a complete program — the output lines carry labels such as `captured`, `replayed:`, `size after reset+write:`.