How to create a zip archive containing google cloud storage objects within appengine java app?

十年热恋 提交于 2019-12-03 20:04:15

I wrote the method below which seems to be working fine.

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();
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!