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.
Code
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
Tar Archive Command BuilderBuild safe tar create, extract, and list commands for gzip, xz, zstd, and bzip2 archives with excludes, target directory (-C), and flag explanations.Git Conventional Commit BuilderBuild and validate Conventional Commits v1.0.0 messages with type, scope, breaking markers, 72-char subject counter, body, footers, and git CLI command.Glob Pattern TesterCompile glob patterns with *, **, ?, character classes, and braces into regex and test them against a list of candidate file paths.
FAQ
- How do you run ZipOutputStream And ZipFile Round Trip?
- It runs as-is — treat the file as the whole program and execute it.
Report a problem with this exampleOpens a pre-filled issue on GitHub.