← 中文资源

简体中文版本

ZipInputStream 读取条目

用 ZipOutputStream 写入两个条目,再用 ZipInputStream 逐条流式读回,读完当前条目后再前进。

阅读英文原文

实现说明

活动部件是类 Main。 循环只出现在 while ((entry = zip.getNextEntry()) != null),它的每次迭代处理一个元素。try-with-resources 保证即使方法体抛出,声明的资源也会被关闭。

使用要点

  • 跑完文件,输出里会留下标记——entries:、archive bytes:。

常见问题

运行「ZipInputStream 读取条目」会打印什么?

文件本身就是完整程序,直接运行——输出行带有 entries:、archive bytes: 这类标签。

核心语句

String content = new String(zip.readAllBytes(), StandardCharsets.UTF_8);
zip.write("first entry\n".getBytes(StandardCharsets.UTF_8));
ByteArrayOutputStream buffer = new ByteArrayOutputStream();

代码示例

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

public class Main {
    public static void main(String[] args) throws IOException {
        ByteArrayOutputStream buffer = new ByteArrayOutputStream();
        try (ZipOutputStream zip = new ZipOutputStream(buffer)) {
            zip.putNextEntry(new ZipEntry("notes.txt"));
            zip.write("first entry\n".getBytes(StandardCharsets.UTF_8));
            zip.closeEntry();
            zip.putNextEntry(new ZipEntry("data/values.csv"));
            zip.write("a,1\nb,2\n".getBytes(StandardCharsets.UTF_8));
            zip.closeEntry();
        }

        // ZipInputStream reads entries in the order they were written
        int entries = 0;
        try (ZipInputStream zip = new ZipInputStream(
                new ByteArrayInputStream(buffer.toByteArray()))) {
            ZipEntry entry;
            while ((entry = zip.getNextEntry()) != null) {
                String content = new String(zip.readAllBytes(), StandardCharsets.UTF_8);
                System.out.println(entry.getName() + " chars=" + content.length());
                zip.closeEntry();
                entries++;
            }
        }

        System.out.println("entries: " + entries);
        System.out.println("archive bytes: " + buffer.size());
    }
}