ZipOutputStream And ZipFile Round Trip

Pack entries into an archive with ZipOutputStream and read names plus recorded sizes back through ZipFile, closing each entry before the zip is finished.

JavaCli Tooling

Code

snippet
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipOutputStream;

public class ReportBundle {

    public static void main(String[] args) throws IOException {
        Path zipPath = Files.createTempFile("report-", ".zip");

        // 打包:putNextEntry → write → closeEntry,条目顺序即写入顺序
        try (ZipOutputStream zip = new ZipOutputStream(Files.newOutputStream(zipPath))) {
            zip.putNextEntry(new ZipEntry("reports/summary.txt"));
            zip.write("orders=42\nrevenue=9100\n".getBytes(StandardCharsets.UTF_8));
            zip.closeEntry();

            zip.putNextEntry(new ZipEntry("reports/errors.txt"));
            zip.write("none\n".getBytes(StandardCharsets.UTF_8));
            zip.closeEntry();
        }

        // 读回:closeEntry 之后 size 与 CRC 才写入条目记录
        try (ZipFile zip = new ZipFile(zipPath.toFile())) {
            zip.entries().asIterator().forEachRemaining(entry ->
                    System.out.println(entry.getName() + " -> " + entry.getSize() + " bytes"));
        }

        Files.deleteIfExists(zipPath);
    }
}

What the code does

ZipOutputStream And ZipFile Round Trip keeps everything in the class ReportBundle.

The try-with-resources form guarantees each declared resource is closed even when the body throws.

Key statements

zip.write("orders=42\nrevenue=9100\n".getBytes(StandardCharsets.UTF_8));
Path zipPath = Files.createTempFile("report-", ".zip");
zip.putNextEntry(new ZipEntry("reports/summary.txt"));

Interactive Tools for This Topic

FAQ

How do you run ZipOutputStream And ZipFile Round Trip?
It runs as-is — treat the file as the whole program and execute it.