将内容流式传输到Google Cloud Storage

问题描述

我想将一个较大的Set<Integer>上传到Google Cloud Storage。我可以这样:

Blob result = storage.create(blobInfo,Joiner.on('\n').join(set).getBytes(UTF_8));

但这会创建一个中间字符串,其中包含所有可能太大的内容
我发现WriteChannel.write()中有example

 Set<Integer> set = ...
 String bucketName = "my-unique-bucket";
 String blobName = "my-blob-name";
 BlobId blobId = BlobId.of(bucketName,blobName);
 byte[] content = Joiner.on('\n').join(set).getBytes(UTF_8);
 BlobInfo blobInfo = BlobInfo.newBuilder(blobId).setContentType("text/plain").build();
 try (WriteChannel writer = storage.writer(blobInfo)) {
     writer.write(ByteBuffer.wrap(content,content.length));
 } catch (IOException ex) {
   // handle exception
 }

但是,如果我这样做,则整个set都将转换为字符串,然后转换为byte[]。字符串本身可能太大。

是否有一个示例,如何遍历该集合并将其转换为ByteBuffer?还是应该对集合中的块进行循环?

解决方法

我能想到的最简单的方法是:

 try (WriteChannel writer = storage.writer(blobInfo)) {
   for(Integer val : set) {
     String valLine = val.toString() + '\n';
     writer.write(ByteBuffer.wrap(valLine.getBytes(UTF_8));
   }
 }

请记住,这不是很有效。它创建了很多小的ByteBuffer。您可以通过写入一个更大的ByteBuffer并定期调用writer.write来大大改善这一点。

,

为避免使用所有字节创建中间字符串,您可以从文件上载。您可以找到示例代码来以各种语言here从文件中上传。