[英]Writing Zip Files to GAE Blobstore
我正在使用Java API读写Google App Engine Blobstore。
我需要将文件直接压缩到Blobstore中,这意味着我有String
对象,要在压缩时将其存储在Blobstore中。
我的问题是标准的压缩方法正在使用OutputStream
进行写入,而GAE似乎没有提供用于写入Blobstore的方法。
是否可以组合使用这些API,或者可以使用其他API(我还没有找到)?
如果我没看错,您可以尝试使用Blobstore低级API 。 它提供了一个Java Channel
( FileWriteChannel
),因此您可以将其转换为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.