我使用Java API对Google App Engine Blobstore进行读写。
我需要将文件直接压缩到Blobstore中,这意味着我有String对象,我希望在压缩时将这些对象存储在Blobstore中。
我的问题是,标准的压缩方法使用OutputStream来编写,而GAE似乎没有提供用于写入Blobstore的压缩方法。
有没有一种方法可以组合这些API,或者我可以使用不同的API(我还没有找到这样的API)?
发布于 2011-11-10 17:02:10
如果我没记错,您可以尝试使用Blobstore low level API。它提供了一个Java Channel (FileWriteChannel),因此您可以将其转换为OutputStream
Channels.newOutputStream(channel)并将该输出流与您当前正在使用的java.util.zip.*类一起使用(here您有一个使用Java NIO将某些内容压缩到Channel/OutputStream的相关示例)
我还没试过。
发布于 2013-01-14 16:46:31
下面是一个编写内容文件并将其压缩并存储到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);
}发布于 2014-01-13 22:15:38
另一种方法是使用BlobStore接口,但目前推荐使用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();
}
}https://stackoverflow.com/questions/8076941
复制相似问题