Bootstrap

向 ZIP 文件中添加文件

import java.io.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class ZipExample {
    private static final int BUFFER_SIZE = 1024;

    public static void main(String[] args) {
        try (ZipOutputStream zos = new ZipOutputStream(new FileOutputStream("output.zip"))) {
            // 添加第一个文件
            compressFile(zos, "file1.txt", "file1.txt");
            // 添加第二个文件
            compressFile(zos, "file2.txt", "file2.txt");

            System.out.println("文件已成功压缩到 output.zip");

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static void compressFile(ZipOutputStream zos, String sourceFilePath, String entryName) throws IOException {
        byte[] buf = new byte[BUFFER_SIZE];
        File sourceFile = new File(sourceFilePath);
        FileInputStream in = null;

        try {
            // 必须调用 putNextEntry 来创建新的 ZIP 条目
            zos.putNextEntry(new ZipEntry(entryName));

            // 将文件内容复制到 ZIP 输出流中
            in = new FileInputStream(sourceFile);
            int len;
            while ((len = in.read(buf)) != -1) {
                zos.write(buf, 0, len);
            }

            // 完成当前 ZIP 实体的写入
            zos.closeEntry();

        } finally {
            if (in != null) {
                in.close();
            }
        }
    }
}

;