java - 如何在 appengine java 应用程序中创建包含谷歌云存储对象的 zip 存档?

标签 java google-app-engine zip google-cloud-storage zipoutputstream

假设我有 50 个对象(每个 15Mb)存储在 Google Cloud Storage 中。现在我需要创建一个包含所有这些文件的 zip 存档并将生成的文件存储回 GCS。 我怎样才能在 Appengine Java 应用程序中做到这一点?

最佳答案

我写了下面的方法,它似乎工作正常。

public static void zipFiles(final GcsFilename targetZipFile,
        final GcsFilename... filesToZip) throws IOException {

    Preconditions.checkArgument(targetZipFile != null);
    Preconditions.checkArgument(filesToZip != null);
    Preconditions.checkArgument(filesToZip.length > 0);

    final int fetchSize = 4 * 1024 * 1024;
    final int readSize = 2 * 1024 * 1024;
    GcsOutputChannel outputChannel = null;
    ZipOutputStream zip = null;
    try {
        GcsFileOptions options = new GcsFileOptions.Builder().mimeType(MediaType.ZIP.toString()).build();
        outputChannel = GCS_SERVICE.createOrReplace(targetZipFile, options);
        zip = new ZipOutputStream(Channels.newOutputStream(outputChannel));
        GcsInputChannel readChannel = null;
        for (GcsFilename file : filesToZip) {
            try {
                final GcsFileMetadata meta = GCS_SERVICE.getMetadata(file);
                if (meta == null) {
                    LOGGER.warning(file.toString() + " NOT FOUND. Skipping.");
                    continue;
                }
                //int fileSize = (int) meta.getLength();
                //  LOGGER.fine("adding " + file.toString());
                ZipEntry entry = new ZipEntry(file.getObjectName());
                zip.putNextEntry(entry);
                readChannel = GCS_SERVICE.openPrefetchingReadChannel(file, 0, fetchSize);
                final ByteBuffer buffer = ByteBuffer.allocate(readSize);
                int bytesRead = 0;
                while (bytesRead >= 0) {
                    bytesRead = readChannel.read(buffer);
                    buffer.flip();
                    zip.write(buffer.array(), buffer.position(), buffer.limit());
                    buffer.rewind();
                    buffer.limit(buffer.capacity());
                }       

            } finally {
                zip.closeEntry();
                readChannel.close();
            }
        }
    } finally {
        zip.flush();
        zip.close();
        outputChannel.close();
    }
}

关于java - 如何在 appengine java 应用程序中创建包含谷歌云存储对象的 zip 存档?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17871412/

相关文章:

java - 强制 HDFS globStatus 跳过它没有权限的目录

linux - 压缩文件并打印到标准输出

java - 无需在 Java 或 Python 中解压缩即可从 ZIP 存档中删除文件

php - 使用 oAuth 处理多个谷歌登录用户

java - 如何在 Java 中将 zip 文件转换为字节

java - 查询 KafkaAvroDeserializer 使用的默认 SchemaRegistryClient

java - eclipse 调试 : Source not found for

java - SQLite android 不创建所有表

java - 如何在 Objectify 上启用 DEBUG 日志记录

google-cloud-storage - 测试对象是否存在于桶中?