使用 Java 云函数在 GCS 存储桶中压缩文件

Zip Files in GCS Bucket Using Java Cloud Function

我正在尝试从 GCS 存储桶中获取一些 files/file 内容,将它们添加到 ZIP 存档中,然后使用 Java 云函数将该存档文件保存在 GCS 存储桶中。

我能够很好地读取文件和写入普通(非 zip)文件。但是,我不清楚如何使用可用的 Java API (bucket.create(String fileName, byte[] content) 到 post ZIP 存档。我有要存档的单个文件的字节数,但如何获取 ZIP 文件本身的字节数?或者我应该看另一个 API?

我在 Java 中找不到任何这样做的例子。我发现 this source about how to do this in Python and this Stack Overflow article 关于如何在 Google App Engine 中执行此操作,但这些都不适用于我的用例。

zip 文件是一个文件。因此,您必须下载所有必须添加到 zip 文件中的文件,创建 zip 文件并将该 zip 文件发送到 GCS。

你可以create ZIP file in JAVA那样。

请记住,/tmp 目录是内存中的一个目录,并且是 Cloud Functions 上的可写目录。因为它在内存中,所以文件的大小加上 zip 的大小不能超过该限制。

我缺少的关键是能够获取正在生成的 ZIP 文件的字节数。您不能直接从 ZipOutputStream 执行此操作,但您可以从“内部”ByteArrayOutputStream(或可能是另一种类型的 OutputStream)中获取字节,如下所示:

byte[] result = null;
try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            ZipOutputStream zipOut = new ZipOutputStream(outputStream)) {
            //Do some writing from wherever you got your content
            zipOut.close();
            outputStream.close();
            result = outputStream.toByteArray();

然后可以将此字节[]写入 GCS。