GZIPInputStream Reads Concatenated Members

Concatenate two gzip streams byte for byte and one GZIPInputStream reads both members back to back, because the format defines multi-member files.

JavaData Integrity

Code

snippet
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.nio.charset.StandardCharsets;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

public class MemberReader {

    public static void main(String[] args) throws Exception {
        ByteArrayOutputStream first = new ByteArrayOutputStream();
        try (GZIPOutputStream gzip = new GZIPOutputStream(first)) {
            gzip.write("first member".getBytes(StandardCharsets.UTF_8));
        }
        ByteArrayOutputStream second = new ByteArrayOutputStream();
        try (GZIPOutputStream gzip = new GZIPOutputStream(second)) {
            gzip.write("second member".getBytes(StandardCharsets.UTF_8));
        }

        // 两段 gzip 原样拼接仍是合法流:GZIPInputStream reads concatenated members back to back
        byte[] concatenated = new byte[first.size() + second.size()];
        System.arraycopy(first.toByteArray(), 0, concatenated, 0, first.size());
        System.arraycopy(second.toByteArray(), 0, concatenated, first.size(), second.size());

        String all = new String(new GZIPInputStream(new ByteArrayInputStream(concatenated))
                .readAllBytes(), StandardCharsets.UTF_8);
        System.out.println("both reads: " + all);
    }
}

What the code does

GZIPInputStream Reads Concatenated Members is built around the class MemberReader.

Resources are declared in a try-with-resources header, so they close on every exit path without a finally block.

Watch out for

  • Nothing to add to the project before running it.

Using it

The run emits 1 labeled section — both reads: — one per step.

Key statements

System.arraycopy(second.toByteArray(), 0, concatenated, first.size(), second.size());
System.arraycopy(first.toByteArray(), 0, concatenated, 0, first.size());
gzip.write("second member".getBytes(StandardCharsets.UTF_8));

Interactive Tools for This Topic

FAQ

What does GZIPInputStream Reads Concatenated Members print when run?
Invoke the file as-is — the `both reads:` prefixes identify which step printed each line.