Read All Bytes And Transfer Streams

Read a small payload into memory with readAllBytes, then stream it between streams with transferTo instead of hand-rolled buffer loops.

JavaData Fetching

Code

snippet
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.zip.GZIPOutputStream;

public class Main {
    public static void main(String[] args) throws IOException {
        // Streams: readAllBytes buffers everything, transferTo copies in chunks
        byte[] compressed;
        try (ByteArrayOutputStream buffer = new ByteArrayOutputStream();
             GZIPOutputStream gzip = new GZIPOutputStream(buffer)) {
            gzip.write("payload ".repeat(16).getBytes(StandardCharsets.UTF_8));
            gzip.finish();
            compressed = buffer.toByteArray();
        }

        byte[] readBack;
        try (InputStream in = new ByteArrayInputStream(compressed)) {
            // readAllBytes:一次读完,只适合已知上限的小负载
            readBack = in.readAllBytes();
        }
        System.out.println("compressed bytes: " + compressed.length);
        System.out.println("read back equal: " + Arrays.equals(compressed, readBack));

        try (InputStream in = new ByteArrayInputStream(compressed);
             ByteArrayOutputStream sink = new ByteArrayOutputStream()) {
            // transferTo:分块复制,不需要手写缓冲区
            long copied = in.transferTo(sink);
            System.out.println("transferred bytes: " + copied);
        }
    }
}

Inside the snippet

Count the class Main as the entire surface area of Read All Bytes And Transfer Streams.

No finally block here — resources declared in the try header close themselves in reverse order.

Using it

Running the file prints labeled results such as compressed bytes:, read back equal:, transferred bytes: — each operation’s effect is visible in the output.

Key statements

gzip.write("payload ".repeat(16).getBytes(StandardCharsets.UTF_8));
compressed = buffer.toByteArray();
long copied = in.transferTo(sink);

Interactive Tools for This Topic

FAQ

What does Read All Bytes And Transfer Streams print when run?
The script runs standalone; its 3 labeled outputs include `compressed bytes:`, `read back equal:`, `transferred bytes:`.