编程语言
首页 > 编程语言> > 如何在AppEngine Java App中创建包含Google云存储对象的zip存档?

如何在AppEngine Java App中创建包含Google云存储对象的zip存档?

作者:互联网

假设我有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();
    }
}

标签:zipoutputstream,google-cloud-storage,google-app-engine,zip,java
来源: https://codeday.me/bug/20191123/2064084.html