创建压缩文件

把 f1.txt 和 f2.txt 压缩为一个 test 压缩文件:
public void yasuoFile() throws Exception {try (ZipOutputStream zos = new ZipOutputStream(new FileOutputStream("test.zip"))) {zos.setLevel(Deflater.BEST_COMPRESSION);ZipEntry ze1 = new ZipEntry("f1.txt");zos.putNextEntry(ze1);BufferedInputStream bis = new BufferedInputStream(new FileInputStream("f1.txt"));byte[] buffer = new byte[1024];int len = -1;while ((len = bis.read(buffer, 0, buffer.length)) != -1) {zos.write(buffer, 0, len);}bis.close();ZipEntry ze2 = new ZipEntry("f2.txt");zos.putNextEntry(ze2);BufferedInputStream bis2 = new BufferedInputStream(new FileInputStream("f2.txt"));byte[] buffer2 = new byte[1024];int len2 = -1;while ((len2 = bis2.read(buffer2, 0, buffer2.length)) != -1) {zos.write(buffer2, 0, len2);}bis2.close();zos.closeEntry();}}
解压压缩文件

在把 test 压缩文件解压到 test 目录下:
public void jieyaFile() throws Exception {try (ZipInputStream zis = new ZipInputStream(new FileInputStream("test.zip"))) {ZipEntry entry = null;while ((entry = zis.getNextEntry()) != null) {String name = entry.getName();String path = "test" + File.separator + name;File file = new File(path);if (!file.getParentFile().exists()) {file.getParentFile().mkdirs();}file.createNewFile();BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));byte[] buffer = new byte[1024];int len = -1;while ((len = zis.read(buffer, 0, buffer.length)) != -1) {bos.write(buffer, 0, len);}bos.close();}}}
读写压缩文件中内容列表
public void list() throws Exception {
// 老版写法
// ZipFile f = new ZipFile("test.zip");
// Enumeration<? extends ZipEntry> e = f.entries();
// while (e.hasMoreElements()) {
// ZipEntry ze = e.nextElement();
// System.out.println(ze.getName());
// }
// 新版写法
ZipFile f = new ZipFile("test.zip");
f.stream().forEach(entry -> System.out.println(entry.getName()));
}
/// 输入的内容:
f1.txt
f2.txt
