Zip Filesystem Read Entries
Open a zip archive as a filesystem with FileSystems.newFileSystem so Path APIs list and read entries without unpacking the archive first.
Code
import java.io.IOException;
import java.nio.file.FileSystem;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.stream.Stream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
public class ZipAsFileSystem {
public static void main(String[] args) throws IOException {
Path zip = Files.createTempFile("bundle-", ".zip");
try (ZipOutputStream out = new ZipOutputStream(Files.newOutputStream(zip))) {
out.putNextEntry(new ZipEntry("conf/app.properties"));
out.write("timeout=30\n".getBytes());
out.putNextEntry(new ZipEntry("conf/db.properties"));
out.write("pool=8\n".getBytes());
}
// zipfs:把 zip 当文件系统打开,Path API 直接列目录、读内容
try (FileSystem zipFs = FileSystems.newFileSystem(zip, (ClassLoader) null);
Stream<Path> entries = Files.list(zipFs.getPath("/conf"))) {
entries.forEach(p -> System.out.println("entry: " + p.getFileName()));
String db = Files.readString(zipFs.getPath("/conf/db.properties"));
System.out.println("db.properties: " + db.strip());
}
Files.delete(zip);
}
}What the code does
Zip Filesystem Read Entries keeps everything in the class ZipAsFileSystem.
The try-with-resources form guarantees each declared resource is closed even when the body throws.
Using it
Running the file prints labeled results such as entry:, db.properties: — each operation’s effect is visible in the output.
Key statements
String db = Files.readString(zipFs.getPath("/conf/db.properties"));
out.putNextEntry(new ZipEntry("conf/app.properties"));
out.putNextEntry(new ZipEntry("conf/db.properties"));
Interactive Tools for This Topic
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.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.
FAQ
- What does Zip Filesystem Read Entries print when run?
- Run it as a complete program — the output lines carry labels such as `entry:`, `db.properties:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.