创建压缩文件

java-zip格式处理 - 图1

把 f1.txt 和 f2.txt 压缩为一个 test 压缩文件:

  1. public void yasuoFile() throws Exception {
  2. try (ZipOutputStream zos = new ZipOutputStream(new FileOutputStream("test.zip"))) {
  3. zos.setLevel(Deflater.BEST_COMPRESSION);
  4. ZipEntry ze1 = new ZipEntry("f1.txt");
  5. zos.putNextEntry(ze1);
  6. BufferedInputStream bis = new BufferedInputStream(new FileInputStream("f1.txt"));
  7. byte[] buffer = new byte[1024];
  8. int len = -1;
  9. while ((len = bis.read(buffer, 0, buffer.length)) != -1) {
  10. zos.write(buffer, 0, len);
  11. }
  12. bis.close();
  13. ZipEntry ze2 = new ZipEntry("f2.txt");
  14. zos.putNextEntry(ze2);
  15. BufferedInputStream bis2 = new BufferedInputStream(new FileInputStream("f2.txt"));
  16. byte[] buffer2 = new byte[1024];
  17. int len2 = -1;
  18. while ((len2 = bis2.read(buffer2, 0, buffer2.length)) != -1) {
  19. zos.write(buffer2, 0, len2);
  20. }
  21. bis2.close();
  22. zos.closeEntry();
  23. }
  24. }

解压压缩文件

java-zip格式处理 - 图2

在把 test 压缩文件解压到 test 目录下:

  1. public void jieyaFile() throws Exception {
  2. try (ZipInputStream zis = new ZipInputStream(new FileInputStream("test.zip"))) {
  3. ZipEntry entry = null;
  4. while ((entry = zis.getNextEntry()) != null) {
  5. String name = entry.getName();
  6. String path = "test" + File.separator + name;
  7. File file = new File(path);
  8. if (!file.getParentFile().exists()) {
  9. file.getParentFile().mkdirs();
  10. }
  11. file.createNewFile();
  12. BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
  13. byte[] buffer = new byte[1024];
  14. int len = -1;
  15. while ((len = zis.read(buffer, 0, buffer.length)) != -1) {
  16. bos.write(buffer, 0, len);
  17. }
  18. bos.close();
  19. }
  20. }
  21. }

读写压缩文件中内容列表

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