将Zip文件写入GAE Blobstore

时间:2011-11-10 08:53:03

标签: java google-app-engine zip blobstore

我正在使用Java API读取和写入Google App Engine Blobstore。

我需要将文件直接压缩到Blobstore中,这意味着我有String个对象,我希望在压缩时将其存储在Blobstore中。

我的问题是标准的压缩方法正在使用OutputStream来编写,而GAE似乎没有提供用于写入Blobstore的方法。

有没有办法合并这些API,或者我可以使用不同的API(我还没有找到)?

3 个答案:

答案 0 :(得分:6)

如果我没错,您可以尝试使用Blobstore low level API。它提供了Java ChannelFileWriteChannel),因此您可以将其转换为OutputStream

Channels.newOutputStream(channel)

并将该输出流与您当前使用的java.util.zip。*类一起使用(here您有一个相关示例,它使用Java NIO将某些内容压缩为Channel / {{ 1}})

我没试过。

答案 1 :(得分:0)

以下是编写内容文件并将其压缩并将其存储到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);
 }

答案 2 :(得分:0)

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

    }
相关问题