3

比方說,我在Google雲端存儲中存儲了50個對象(每個15Mb)。現在我需要創建一個包含所有這些文件的zip文件,並將結果文件存回GCS。 我該如何從appengine java應用程序中做到這一點?如何在appengine java應用程序中創建一個包含Google雲存儲對象的zip存檔?

+0

您可以使用ZipOutputStream。 [這個答案](http://stackoverflow.com/a/13772805/624900)有你需要開始的大部分。 – jterrace

+0

根據您的建議寫上述方法。只是不知道如何檢查數據完整性。 –

+0

您應該將其作爲答案發布,而不是在問題中發佈。誠信是什麼意思? – jterrace

回答

3

我寫了下面的方法似乎工作正常。

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(); 
    } 
} 
+0

當拉鍊大於30M所允許的尺寸時,我該怎麼辦? – RCB

相關問題