ZipInputStream Reads Entries

Write two entries with ZipOutputStream, then stream them back through ZipInputStream and read each entry before advancing.

JavaData Integrity

Code

snippet
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());
    }
}

Inside the snippet

ZipInputStream Reads Entries reduces to the class Main.

The cycling part of this snippet is while ((entry = zip.getNextEntry()) != null). try-with-resources closes each declared resource automatically on every exit path.

Watch out for

  • There is no dependency tree here — the platform is the whole dependency.

Putting it to use

Look for the entries:, archive bytes: prefixes when the file runs; they tie each line to its step.

Core lines

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

Interactive Tools for This Topic

FAQ

What does ZipInputStream Reads Entries print when run?
Running the file directly is enough — expect labeled output lines such as `entries:`, `archive bytes:`.