2011-11-10 95 views
2

我正在使用Java API讀取和寫入Google App Engine Blobstore。將Zip文件寫入GAE Blobstore

我需要將文件直接壓縮到Blobstore中,這意味着我有String對象,我想在壓縮時將其存儲在Blobstore中。

我的問題是標準的壓縮方法使用OutputStream來編寫,而GAE似乎沒有提供寫入Blobstore的方法。

有沒有一種方法來結合這些API,或者是否有我可以使用的不同API(我還沒有找到)?

回答

6

如果我沒有錯,您可以嘗試使用Blobstore low level API。它提供了一個Java ChannelFileWriteChannel),那麼你也許可以將其轉換爲OutputStream

Channels.newOutputStream(channel) 

,並使用該輸出流與java.util.zip *您當前使用的類(here你有相關的例子,使用Java NIO的東西拉到Channel/OutputStream

我還沒有嘗試過。

+0

感謝,它幫助! – user1039343

+1

我看到你是這裏的新用戶。您應該將答案標記爲已接受,以解決您的問題。這也有助於其他人。 –

0

下面是一個例子寫的內容文件和壓縮,並將其存儲到Blob存儲區:

AppEngineFile file = fileService.createNewBlobFile("application/zip","fileName.zip"); 

try { 

    FileWriteChannel writeChannel = fileService.openWriteChannel(file, lock); 

    //convert as outputstream 
    OutputStream blobOutputStream = Channels.newOutputStream(writeChannel); 

    ZipOutputStream zip = new ZipOutputStream(blobOutputStream);      

    zip.putNextEntry(new ZipEntry("fileNameTozip.txt")); 

    //read the content from your file or any context you want to get 
    final byte data[] = IOUtils.toByteArray(file1InputStream);      

    //write byte data[] to zip 
     zip.write(bytes); 

    zip.closeEntry();      
    zip.close(); 

    // Now finalize 
    writeChannel.closeFinally(); 
} catch (IOException e) { 
    throw new RuntimeException(" Writing file into blobStore", e); 
} 
0

對方回答是使用Blob存儲區API,但是目前推薦的方法是使用App Engine的GCS客戶端。

下面是我用它來壓縮在GCS多個文件:

public static void zipFiles(final GcsFilename targetZipFile, 
          Collection<GcsFilename> filesToZip) throws IOException { 

    final GcsFileOptions options = new GcsFileOptions.Builder() 
      .mimeType(MediaType.ZIP.toString()).build(); 
    try (GcsOutputChannel outputChannel = gcsService.createOrReplace(targetZipFile, options); 
     OutputStream out = Channels.newOutputStream(outputChannel); 
     ZipOutputStream zip = new ZipOutputStream(out)) { 

     for (GcsFilename file : filesToZip) { 
      try (GcsInputChannel readChannel = gcsService.openPrefetchingReadChannel(file, 0, MB); 
       InputStream is = Channels.newInputStream(readChannel)) { 
       final GcsFileMetadata meta = gcsService.getMetadata(file); 
       if (meta == null) { 
        log.warn("{} NOT FOUND. Skipping.", file.toString()); 
        continue; 
       } 
       final ZipEntry entry = new ZipEntry(file.getObjectName()); 
       zip.putNextEntry(entry); 

       ByteStreams.copy(is, zip); 
       zip.closeEntry(); 
      } 
      zip.flush(); 
     } 

    }