ZipOutputStream STORED Entry Needs Size And CRC

Zip STORED entries skip the deflater but the ZIP format demands size and CRC up front, so set both on the entry before writing its bytes.

JavaData Integrity

Code

snippet
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.nio.charset.StandardCharsets;
import java.util.zip.CRC32;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;

public class StoredArchive {

    public static void main(String[] args) throws Exception {
        ByteArrayOutputStream sink = new ByteArrayOutputStream();
        byte[] payload = "already sized payload".getBytes(StandardCharsets.UTF_8);

        CRC32 crc = new CRC32();
        crc.update(payload);

        ZipOutputStream zip = new ZipOutputStream(sink);
        // STORED needs size and CRC up front:ZIP 格式要求写入前先报这两个元数据
        ZipEntry stored = new ZipEntry("blob.bin");
        stored.setMethod(ZipEntry.STORED);
        stored.setSize(payload.length);
        stored.setCrc(crc.getValue());
        zip.putNextEntry(stored);
        zip.write(payload);
        zip.closeEntry();
        zip.close();

        try (ZipInputStream in = new ZipInputStream(new ByteArrayInputStream(sink.toByteArray()))) {
            ZipEntry entry = in.getNextEntry();
            System.out.println("entry: " + entry.getName());
            System.out.println("method: " + (entry.getMethod() == ZipEntry.STORED ? "STORED" : "DEFLATED"));
            System.out.println("size: " + entry.getSize());
            System.out.println("crc matches: " + (entry.getCrc() == crc.getValue()));
        }
    }
}

How this snippet works

ZipOutputStream STORED Entry Needs Size And CRC keeps everything in the class StoredArchive.

Resources live in the try header, so closing is compiler-generated and exception-safe.

Caveats

  • No lockfile entry, no version pinning — the file needs nothing beyond the runtime.

Applying it

The run announces its steps in the output: entry:, method:, size:.

Statements that matter

byte[] payload = "already sized payload".getBytes(StandardCharsets.UTF_8);
ByteArrayOutputStream sink = new ByteArrayOutputStream();
ZipOutputStream zip = new ZipOutputStream(sink);

Interactive Tools for This Topic

FAQ

What does ZipOutputStream STORED Entry Needs Size And CRC print when run?
The script runs standalone; its 4 labeled outputs include `entry:`, `method:`, `size:`.