簡體   English   中英

將Zip文件寫入GAE Blobstore

[英]Writing Zip Files to GAE Blobstore

我正在使用Java API讀寫Google App Engine Blobstore。

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

我的問題是標准的壓縮方法正在使用OutputStream進行寫入,而GAE似乎沒有提供用於寫入Blobstore的方法。

是否可以組合使用這些API,或者可以使用其他API(我還沒有找到)?

如果我沒看錯,您可以嘗試使用Blobstore低級API 它提供了一個Java ChannelFileWriteChannel ),因此您可以將其轉換為OutputStream

Channels.newOutputStream(channel)

並將該輸出流與當前使用的java.util.zip。*類一起使用( 這里有一個相關示例,該示例使用Java NIO將某些內容壓縮到Channel / OutputStream )。

我沒有嘗試過。

這是一個編寫內容文件並將其壓縮並將其存儲到blobstore的示例:

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);
 }

另一個答案是使用BlobStore 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();
        }

    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM